BlogCFC - Counting Words in an entry

Word Count: 242
I thought I would add a quick feature to my blog today. I wanted to be able to display the number of words per post. This was way easier than I thought it would be and it was mainly because of the power behind Regular Expressions. I am still new to regex so this may not be completely right but it works so I am going with it. To add this feature to your blog you have to add 1 line in your index on the same line where it displays the date and tags, here is the code.
<cfoutput>| Word Count: #application.blog.getWordCount(body)#</cfoutput>

Then you need to add the following function to the main BlogCFC Component. All we are doing here is reading the entry text, stripping the html tags and counting the words using Java's String method split. The split method actually returns an array of words so a quick arrayLen() will give us the count we are looking for.
<cffunction name="getWordCount" access="public" output="true" returntype="numeric">
   <cfargument name="str" type="string" required="true">
   <cfset var stripped = REReplace(arguments.str, "<.*?>", "", "all")>
   <cfset var words = stripped.split('\W')>
   <cfreturn arrayLen(words)>
</cffunction>

Finally just clear the cache by appending ?reinit=1 to the url.

Comments

#1 Posted By: Todd Rafferty Posted On: 8/9/07 3:09 PM
Is word count really important or is it just trivial data?
#2 Posted By: Dan Posted On: 8/9/07 3:15 PM |
Author Comment
I would say its almost worthless on a entry by entry basis. If you were able to modify the addEntry method to add word count to the database then it may come into play when running reports. For those of us just using it to express our thoughts and ideas it may not be useful but hopefully someone out there will find a need for it. It was a small enough change so i just did it.
#3 Posted By: Rey Bango Posted On: 8/11/07 6:04 PM
Hey Dan, check out these jQuery plugins which are kind of in the same neighborhood as your post:

jQuery wordStats: Tries to determine what a page is about by computing the density of its keywords.
http://www.hovinne.com/blog/index.php/2007/08/09/1...

DynaCloud – a dynamic JavaScript tag/keyword cloud with jQuery
http://johannburkard.de/blablog/programming/javasc...

I just thought these were cool plugins...well, in reality I'm trying to convert you to jQuery (www.jquery.com)! LOL!
#4 Posted By: Dan Vega Posted On: 8/16/07 3:09 PM |
Author Comment
Rey,
You may convert me to jquery one day. I was just checking out the tablesorter demo and I am really digging it.


Post Your Comment

Leave this field empty







Show Captcha

If you subscribe, any new posts to this thread will be sent to your email address.

Copyright © 2007 Dan Vega | BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.