Python:替换fi中的行时遇到问题

2024-04-27 21:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图建立一个翻译使用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. 

将通知帮助:) 谢谢。你知道吗


Tags: 文件forinputoutputopentranslatefiledeepl
1条回答
网友
1楼 · 发布于 2024-04-27 21:07:36

您正在以r+模式打开fileresp。调用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")

相关问题 更多 >