lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 21 January 2015 at 10:29, Rena <hyperhacker@gmail.com> wrote:
> On Wed, Jan 21, 2015 at 2:33 AM, DouOlivia <olivia2046@hotmail.com> wrote:
>> Hi there,
>>
>> Should have performed a search in the list first, but I’m afraid I cannot
>> come out with a good query. Here’s the question: Is there a library that can
>> calculate the ratio of numberic or alphanumeric words in a given string (the
>> actual scenario is to use a document’s content so the string will be very
>> long)? E.g  for string “34 aaa A-7SXD bbb ccc”, the ratio is calculated as
>> 0.4.
>
> Seems like a simple task for Lua's pattern matching:
>
> function countMatches(str, pat)
>     local c = 0
>     for word in str:gmatch(pat) do c = c + 1 end
>     return c
> end

Couldn't resist... this version of countMatches() is shorter and
faster (on my machine at least) in long documents:

function countMatches(str, pat)
    return select(2, str:gsub(pat, "%0"))
end

function ratio(text)
        return countMatches(text, '%d+') / countMatches(text, '[%a%p]+')
end

Regards,
Matthew