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)
注意:代碼未經測試。
添加回答
舉報