Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

python - How to replace a specific line in a file?

I have 2 xlf files, one correct (in French) and one with some errors in some tags (in English). I have to take tags in the french file, and then replace matching tags content in the english file. The problem here is that theese files don't have the same line number.

From what I have down here, I managed to make the matching but I didn't succeeded on replacing the text in the english file.

Here is my code :

import re
pattern = re.compile('(?<=<x).*?(?=/>)')
fin = open("French.xlf")
fout = open("English.xlf", 'r')
matches = []

for line in fin:
    matches.extend(re.findall(pattern, line))

for line in fout:
    for i, match in enumerate(pattern.findall(line)):
        newLine = line.replace(match, matches[i])
        print(pattern.findall(line))
        print(match," to ", matches[i])
        print(newLine)

fin.close()
fout.close()
question from:https://stackoverflow.com/questions/66046576/how-to-replace-a-specific-line-in-a-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...