[英]Lua how to split a word pair string into two separate variables?
我有这个代码,它读取一个 txt 文件,该文件仅包含每行上由空格分隔的单词对列表,对于每一行,代码会将单词对拆分为单独的单词并一个接一个地打印每个单词:
file = io.open( "test.txt", "r" )
temp = {}
for line in file:lines() do
for word in line:gmatch("%w+") do
print(word)
end
end
file:close()
样本 test.txt
big small
tall short
up down
left right
output
big
small
tall
short
up
down
left
right
但是,我发现自己需要将每个单词对中的每个单词拆分为单独的变量,以便我可以在 word1 上使用 if 语句来对 word2 执行某些操作。
就像是:
file = io.open( "test.txt", "r" )
temp = {}
for line in file:lines() do
for word in line:gmatch("%w+") do
word1 = first word
word2 = second word
if (word1 = "tall") then
print(word2)
end
end
end
file:close()
我自己没有在 Lua 中编程,所以如果以下代码有问题,请提前道歉
file = io.open( "test.txt", "r" )
temp = {}
for line in file:lines() do
words = {}
for word in line:gmatch("%w+") do table.insert(words, word) end
if (words[1] == "tall") then
print(words[2])
end
end
file:close()
对您提供的测试文件运行此命令会返回“ short
”一词,我认为这就是您所需要的?
对于几句话,您可以使用捕获。 这种机制允许获取匹配的特定部分。
见https://www.lua.org/manual/5.4/manual.html#6.4.1
local w1, w2 = line:match("(%w+)%s+(%w+)")
或者,特别是对于许多单词,您会将所有单词放入一个表中。
local line_words = {}
for word in line:gmatch("%w+") do
table.insert(line_words, word)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.