为什么函数 io.write() 在 lua 中不起作用
why the function io.write() does not work in lua
我想统计一段文字出现的次数,并给出前十个词及其出现次数。
我使用函数 io.open() 打开一个输入文件作为文件句柄,然后在文件句柄上做一些事情,将结果放在 table 中。然后关闭输入文件句柄。并打开一个作为文件句柄的新文件的输出文件,尝试将结果写入该文件。但它不起作用。代码如下。
txt“ioinput.txt”是包含文章的输入文件,txt“iooutput.txt”是输出文件
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()
请参考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.
请注意,可选模式将作为字符串提供。
在你的代码中
input_file = io.open("ioinput.txt", r)
和 output_file = io.open("ioinput.txt", a)
您的使用模式 r
和 a
。均为零值。模式默认为 "r"
,即读取模式。您无法写入以读取模式打开的文件。
我想统计一段文字出现的次数,并给出前十个词及其出现次数。
我使用函数 io.open() 打开一个输入文件作为文件句柄,然后在文件句柄上做一些事情,将结果放在 table 中。然后关闭输入文件句柄。并打开一个作为文件句柄的新文件的输出文件,尝试将结果写入该文件。但它不起作用。代码如下。
txt“ioinput.txt”是包含文章的输入文件,txt“iooutput.txt”是输出文件
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()
请参考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.
请注意,可选模式将作为字符串提供。
在你的代码中
input_file = io.open("ioinput.txt", r)
和 output_file = io.open("ioinput.txt", a)
您的使用模式 r
和 a
。均为零值。模式默认为 "r"
,即读取模式。您无法写入以读取模式打开的文件。