簡體   English   中英

Lua 如何將單詞對字符串拆分為兩個單獨的變量?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM