Reputation: 25
I want to count the number of occurrences of words in a text and give the top ten words and their number of occurrences.
I use the function io.open() to open a input file as file-handle, then do something on the file-handle, put the results in a table. then close the input file-handle. and open a output file which is a new file as file-handle try to write the results to this file. but it does not work. the code is following.
the txt "ioinput.txt" is input file which has a article and the txt "iooutput.txt" is the output file
input_file = io.open("ioinput.txt", r)
--[[
This block of code is to count the number of word,
which has been verified by the print function in the following.
--]]
input_file:close()
output_file = io.open("iooutput.txt", a)
local n = 10
for i = 1, n do
output_file:write(words[i], "\t", counter[words[i]], "\n")
--print(words[i], "\t", counter[words[i]], "\n")
end
output_file:flush()
output_file:close()
Upvotes: 0
Views: 315
Reputation: 28950
Please refer to the Lua 5.4 Reference Manual: io.open
io.open (filename [, mode])
This function opens a file, in the mode specified in the string mode. In case of success, it returns a new file handle.
The mode string can be any of the following:
"r": read mode (the default); "w": write mode; "a": append mode; "r+": update mode, all previous data is preserved; "w+": update mode, all previous data is erased; "a+": append update mode, previous data is preserved, writing is only allowed at the end of file.
The mode string can also have a 'b' at the end, which is needed in some systems to open the file in binary mode.
Please note that the optional mode is to be provided as a string.
In your code
input_file = io.open("ioinput.txt", r)
and output_file = io.open("ioinput.txt", a)
your using modes r
and a
. Both nil values. The mode defaults to "r"
which is read mode. You cannot write to a file opened in read mode.
Upvotes: 1