3

我正在尝试使用 deepl 为字幕构建翻译器,但它运行不完美。我设法翻译了字幕,并且大部分部分我在更换台词时遇到了问题。我可以看到这些行已被翻译,因为它会打印它们但不会替换它们。每当我运行程序时,它都与原始文件相同。

这是负责的代码:

def translate(input, output, languagef, languaget):
    file = open(input, 'r').read()
    fileresp = open(output,'r+')
    subs = list(srt.parse(file))
    for sub in subs:
        try:
            linefromsub = sub.content
            translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper())
            print(str(sub.index) + ' ' + translationSentence)
            for line in fileresp.readlines():
                newline = fileresp.write(line.replace(linefromsub,translationSentence))
        except IndexError:
            print("Error parsing data from deepl")

这是文件的外观:

1
00:00:02,470 --> 00:00:04,570
        - Yes, I do.
        - (laughs)

2
00:00:04,605 --> 00:00:07,906
      My mom doesn't want
      to babysit everyday

3
00:00:07,942 --> 00:00:09,274
        or any day.

4
00:00:09,310 --> 00:00:11,977
        But I need
    my mom's help sometimes.

5
00:00:12,013 --> 00:00:14,046
        She's just gonna
    have to be grandma today. 

帮助将不胜感激 :) 谢谢。

4

1 回答 1

3

您正在filerespr+模式打开。当您调用readlines()时,文件的位置将设置为文件的末尾。随后的调用write()将附加到文件中。如果你想覆盖原始内容而不是追加,你应该试试这个:

allLines = fileresp.readlines()
fileresp.seek(0)    # Set position to the beginning
fileresp.truncate() # Delete the contents
for line in allLines:
    fileresp.write(...)

更新

在这里很难看到你想用r+mode 完成什么,但似乎你有两个单独的输入和输出文件。如果是这种情况,请考虑:

def translate(input, output, languagef, languaget):
    file = open(input, 'r').read()
    fileresp = open(output, 'w') # Use w mode instead
    subs = list(srt.parse(file))
    for sub in subs:
        try:
            linefromsub = sub.content
            translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper())
            print(str(sub.index) + ' ' + translationSentence)
            fileresp.write(translationSentence) # Write the translated sentence
        except IndexError:
            print("Error parsing data from deepl")
于 2017-12-09T17:38:37.607 回答