You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用字典替换文件词汇并生成新文件?含字典文件加载方案

Lua 实现词汇本地化替换完整方案

1. 从TSV文件加载翻译字典

实现读取dict.tsv的函数,按制表符分割每行的英文和德语词汇,生成可用于查找的字典:

-- 从TSV文件加载翻译字典
function loadDictFromTSV(filePath)
    local dict = {}
    local file = io.open(filePath, "r")
    if not file then error("无法打开字典文件: " .. filePath) end
    
    for line in file:lines() do
        -- 匹配制表符分隔的英文和德语词汇,跳过格式错误的行
        local enWord, deWord = line:match("^([^\t]+)\t([^\t]+)$")
        if enWord and deWord then
            -- 去除词汇首尾空白字符
            dict[enWord:trim()] = deWord:trim()
        end
    end
    file:close()
    return dict
end

-- 给字符串扩展去除首尾空白的方法
function string:trim()
    return self:gsub("^%s+", ""):gsub("%s+$", "")
end

2. 处理英文本地化文件生成德语版本

读取locale_EN.txt的每行单词,用字典完成替换,将结果写入locale_DE.txt:

-- 处理本地化文件,完成词汇替换并保存
function processLocaleFile(inputPath, outputPath, dict)
    local inputFile = io.open(inputPath, "r")
    if not inputFile then error("无法打开输入文件: " .. inputPath) end
    
    local outputFile = io.open(outputPath, "w")
    if not outputFile then 
        inputFile:close()
        error("无法创建输出文件: " .. outputPath) 
    end
    
    -- 逐行读取处理
    for line in inputFile:lines() do
        local word = line:trim()
        -- 找到翻译就替换,找不到保留原词
        local translated = dict[word] or word
        outputFile:write(translated .. "\n")
    end
    
    inputFile:close()
    outputFile:close()
end

3. 执行主流程

将上述函数串联,一键完成整个替换流程:

-- 加载字典
local translationDict = loadDictFromTSV("dict.tsv")
-- 生成德语本地化文件
processLocaleFile("locale_EN.txt", "locale_DE.txt", translationDict)
print("德语本地化文件 locale_DE.txt 已生成!")

额外说明

  • 原performLookup函数用于处理数组,可修改为单词版本复用:
    function performLookup(word, dict)
        return dict[word] or word
    end
    
  • 代码包含基础的文件异常判断,可根据实际需求扩展错误处理逻辑
  • 确保dict.tsv每行格式为英文单词\t德语翻译,避免多余制表符或空白导致加载失败

内容的提问来源于stack exchange,提问作者darkfrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:42:28