Qt 如何从 .ts 文件提取所有源文
在Qt中,.ts
文件本身就是用来存储源文(Source Text)和对应翻译的。.ts
文件中的<source>
标签包含了从你的源代码中提取出来的原始字符串(即源文)。因此,.ts
文件已经“包含”了所有需要翻译的源文。
但如果你的目标是提取或导出这些源文(例如,为了交给翻译人员、进行文本分析、或生成一个纯文本列表),有以下几种方法:
使用 lconvert
工具 (推荐)
Qt提供了一个强大的命令行工具 lconvert
,可以用来转换和操作翻译文件。你可以用它将.ts
文件转换成纯文本格式(.po
或 .pot
),然后从中提取源文。
-
转换为 .pot (Portable Object Template) 文件:
.pot
文件只包含源文,没有翻译。这正是你想要的。lconvert -i myapp_zh_CN.ts -o myapp_sources.pot
-i
: 输入文件-o
: 输出文件lconvert
会自动将.ts
转换为.pot
格式。
-
从 .pot 文件提取源文:
.pot
文件也是文本文件,但结构清晰。你可以用简单的文本处理工具(如grep
,awk
,sed
)或脚本提取msgid
行(msgid
对应源文)。使用 grep (Linux/macOS/WSL):
# 提取所有 msgid 行,并去除 msgid 前缀和引号 grep '^msgid ' myapp_sources.pot | sed 's/^msgid "//; s/"$//' > all_sources.txt
使用 findstr (Windows 命令提示符):
findstr /B "msgid " myapp_sources.pot > temp.txt REM 你需要手动或用其他工具(如 PowerShell)处理 temp.txt,去除 "msgid " 和引号
使用 PowerShell (Windows):
Select-String -Path "myapp_sources.pot" -Pattern '^msgid "(.*)"' | ForEach-Object { $_.Matches[0].Groups[1].Value } | Out-File -FilePath "all_sources.txt" -Encoding UTF8
流程
- 打开 Qt 自带命令窗口
- cd /d 到.ts文件目录
- 运行命令 lconvert -i myapp_zh_CN.ts -o myapp_sources.pot
- 打开windows自带命令窗口,cd 到 myapp_sources.pot文件目录
- 运行命令 findstr /B "msgid " myapp_sources.pot > temp.txt
emp.txt 文件如下: