How to count the amount of words in a text file in Lua
Asked Answered
M

1

5

I was wanting to ask what the steps are to creating a Lua program that would count the amount of words in a .txt file? I'm only familiar with how to count characters and not strings.

Mechanism answered 18/3, 2015 at 21:53 Comment(4)
counting words accurately is tricky, there are so many edge cases with hyphens and em dashes etc. A simple one might use string.gfindOriginality
Check out the book Programming in Lua (which has a free version online) - program to count the number of characters, words, and lines in a file: lua.org/pil/21.2.1.htmlHull
@rpattiso, string.gfind has been renamed string.gmatch since then.Hwahwan
@Hwahwan sorry, looks like 5.0 was the last appearance of string.gfindOriginality
H
9

A sequence of nonspace characters is a good approximation to what a word is.

In that case, this simple code counts the words in a string s:

_,n = s:gsub("%S+","")
print(n)

This works because gsub returns the number of substitutions made as a second result. This count is rarely used, and sometimes even a minor annoyance, but in this case it's exactly what is needed.

Hwahwan answered 19/3, 2015 at 3:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.