问题描述
尝试开发可以将文件中的内容自动翻译成不同语言但只希望在标记区域之间进行翻译的东西。问题是:我可以指定 .read 只在我们说“”之间读取吗?
在我的文件中,我有一个句子或单词的列表,甚至可以说字母,它们就在那里。我在句子或要翻译的单词周围加上了“”语音标记。
下面是我的txt文件:
Sentence 1 - "I like Bannannas and I will eat them all day."
Sentence 2 - How is your day going?
Sentence 3 - "Will there be any sort of fun today or just raining?"
Sentence 4 - Can the sun come out to play!!!
我希望能够翻译现在只包含在 "" 周围的句子。
我目前的代码:
import re
import googletrans
from googletrans import Translator
file_translator = Translator()
tFile = open('demo.txt','r',encoding="utf-8")
if tFile.mode == 'r':
content = tFile.read()
print(content)
result = file_translator.translate(content,dest='fr')
with open('output.txt','w') as outFile:
outFile.write(result.text)
解决方法
首先我们要在文件中找到正确的句子,因此我们使用 re
找到文本,然后我们必须使用 googletrans
翻译该文本,然后我们必须替换找到的句子和翻译的句子,最后我们可以在文本文件中写出整个段落。
这是完成所有这些事情的代码:
import re
import googletrans
from googletrans import Translator
file_translator = Translator()
with open("demo.txt","r") as f:
content=f.read()
pattern=re.compile(r'"([^"]*)"',re.MULTILINE)
founds=re.findall(pattern,content)
translated=[]
for found in founds:
translated.append(file_translator.translate(found,dest='fr').text)
for f,t in zip(founds,translated):
content=content.replace(f'"{f}"',t)
with open('output.txt','w') as outFile:
outFile.write(content)