如何用字典替换文件中的单词并保存到文件中?

问题描述 投票:0回答:1

A 有一本字典作为

dict = {
    body = "Körper",
    child = "Kind",
    eye = "Auge"
    face = "Gesicht"
}

我有类似查找功能的东西:

function performLookup(words, dict)
    for i, word in ipairs(words) do
        if dict[word] then
            words[i] = dict[word]
        end
    end
end

如何打开文件,找到该行(一行只有一个单词)并将其保存到其他文件?理想情况下,字典也必须位于文件中并作为查找表加载。

lua lookup
1个回答
1
投票

我可能误解了这个问题,但我有这个:

function performLookup(words, dict)
    for i, word in ipairs(words) do
        if dict[word] then
            words[i] = dict[word]
        end
    end
end

function readFile(fname)
    local dict = {}
    local words = {}
    local file = io.open(fname, "r")
    local line = file:read("*line")
    while line ~= "" do
        local english, german = line:match("(%S+)%s+(%S+)")
        dict[english] = german
        line = file:read("*line")
    end
    while line do
        line = file:read("*line")
        table.insert(words, line)
    end
    file:close()
    return dict, words
end

function writeFile(fname, dict, words)
    file = io.open(fname, "w")
    performLookup(words, dict)
    for i, line in ipairs(words) do
        file:write((i == 1 and "" or "\n") .. line) 
    end
    file:close()
end

dict, words = readFile("original.txt")
writeFile("modified.txt", dict, words)

输入文件(original.txt)如下所示:

body Körper
child Kind
eye Auge
face Gesicht

some
random
words
eye
and
a
few
more
face

输出文件(modified.txt)如下所示:

some
random
words
Auge
and
a
few
more
Gesicht

这个问题可以更清楚,但这就是您想要的吗?还需要一些错误检查,因为它假定格式正确。

© www.soinside.com 2019 - 2024. All rights reserved.