Sample Program 2


Description

This program uses two techniques to count the number of words in the selected itme text. The first uses an algrithm based on the number of characters and then dividing by 6 the second uses regular expressions to count the number of words by ... counting the number of words (excluding numbers). This later is a unique way of solving the problem in a single line of code. The first variation is a detail of counting the words in one item of text and the variation on the theme will count the text for any selection of items returning the individual itme counts and the total count.

First Variation

--
-- Ecco LUA extension
-- copy into luacmd.lua in the ecco directory
--
-- assign to the tool menu as a document
--
-- by Larry Yudelson, ads@yudel.com November 2007
--
--
--

function wordCount()
fullText=" "
NumberItems=get_select_items()
MaxItems=table.maxn(NumberItems)

msgbox(MaxItems .. " items selected","")
for i=1,MaxItems do

-- y=tostring(i)..", "..get_item_text(NumberItems[i]).."\n"

thisText = get_item_text(NumberItems[i])
fullText= thisText.." " ..fullText
end -- next i

len=string.len(fullText)

-- count it with string.len(variable)

wc=len/6
msgbox("item has "..len.." chars and "..wc.." words!","")

-- let's initalize the variables for this string

wc=0 -- start with no words

-- looks like we could do it with a REGEX

for w in string.gmatch(fullText, "%a+") do
wc=wc+1
end -- next w
msgbox(wc.." words found","ECCO WC")

end

--- end wordCount


Variation on a theme

This variation dervies from Sample Rule 6 but extend it to sum the word count over a series of items including subitems. This code only displays the values but it is possible to either store the value in a folder or in an external file. To store the value in a folder use the set_folder_value() function. Alternatively it is possible to create a new line item or subitem in which case teh set_item_text() and create_sub_item() would be useful.

function WordCountExt()
NumberItems=get_select_items()
MaxItems=table.maxn(NumberItems)
msgbox(MaxItems .. " items selected","")
tc=0.
for i=1,MaxItems do
wc=0.
for w in string.gmatch(get_item_text(NumberItems[i]),"%a+") do
wc=wc+1
end
msgbox(wc.." item "..tostring(i).." word count","")
tc=tc+wc
end
msgbox(tc.." total Word Count","")
end



[Back to sample LUA programs]