This code takes in a web url (nytimes.com), and outputs a list of the top 10 word occurrences and the number of times they appear. I am getting the top 10 words, but I am getting nil for the count. Can someone help me fix the count variable to display the number of occurrences? Thanks!
local http = require("socket.http")
local url = "http://www.nytimes.com"
local body = http.request(url)
local words = {}
for word in string.gmatch(body,"%a+") do
-- print(word)
words[word] = (words[word] or 0) + 1
end
for word, count in pairs(words) do
-- print(words,count)
end
function top1(t)
local max = 0
local maxword
for word, count in pairs(t) do
if count > max then
max = count
maxword = word
end
end
t[maxword] = nil
return maxword, count
end
for i = 1, 10 do
print(top1(words))
end
You’re returning the wrong variable from top1() –
return maxword, countshould bereturn maxword, max.