1 回答

TA贡献1825条经验 获得超4个赞
简而言之,您有两个问题:
如何正确替换文件的第 2(和 3)行。
如何跟踪更改的单词数。
如何正确替换文件的第 2(和 3)行。
你的代码:
with open(Path + i,"w") as f:
for line in file:
if line == second_line:
f.write(res)
未启用阅读。for line in file不管用。f已定义,但file改为使用。要解决此问题,请改为执行以下操作:
with open(Path + i,"r+") as file:
lines = file.read().splitlines() # splitlines() removes the \n characters
lines[1] = second_line
file.writelines(lines)
但是,您想向其中添加更多行。我建议你以不同的方式构建逻辑。
如何跟踪更改的单词数。
添加变量changed_words_count并在old_word != new_word
结果代码:
for i in filelist:
filepath = Path + i
# The lines that will be replacing the file
new_lines = [""] * 3
with open(filepath, "r", encoding="utf-8") as file:
data = file.readlines()
first_line = data[0]
second_line = data[1]
second_line_array = second_line.split(" ")
changed_words_count = 0
for j in range(nb_words_to_replace):
replacement_position = randrange(len(second_line_array))
old_word = second_line_array[replacement_position]
new_word = new_words[randrange(len(new_words))]
# A word replaced does not mean the word has changed.
# It could be replacing itself.
# Check if the replacing word is different
if old_word != new_word:
changed_words_count += 1
second_line_array[replacement_position] = new_word
# Add the lines to the new file lines
new_lines[0] = first_line
new_lines[1] = " ".join(second_line_array)
new_lines[2] = str(changed_words_count)
print(f"Result: {new_lines[1]}")
with open(filepath, "w") as file:
file.writelines(new_lines)
注意:代码未经测试。
添加回答
举报