Python:无法从文件中替换行

时间:2017-12-09 17:28:58

标签: python python-3.x deepl

我正在尝试使用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. 

帮助将被appuraciated :) 感谢。

1 个答案:

答案 0 :(得分:2)

您正在使用fileresp模式打开r+。当您致电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+模式下尝试完成的操作,但似乎您有两个独立的输入和输出文件。如果是这种情况,请考虑:

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")