テキストファイルを一度しか更新できない関数を書きますが、繰り返し実行する必要があります。一時ファイルをターゲットファイルに頻繁にコピーすることを避けるために、ループ内のすべての単語を一度だけ更新したいのですが、どうすればいいですか?例えばPythonのループでテキストファイルを更新する方法
import io
from tempfile import mkstemp
from shutil import move
from os import remove, close
def replaceWords(source_file_path, old_word, cluster_labels):
new_word_list = [old_word + "_" + str(label) for label in cluster_labels]
fh, target_file_path = mkstemp()
with io.open(target_file_path, mode='w', encoding='utf8') as target_file:
with io.open(source_file_path, mode='r', encoding='utf8') as source_file:
index = 0
for line in source_file:
words =[]
for word in line.split():
if word == old_word:
words.append(word.replace(old_word, new_word_list[index]))
index += 1
else:
words.append(word)
target_file.write(" ".join(words))
close(fh)
remove(source_file_path)
move(target_file_path, source_file_path)
:最初の更新のための
:
ソースファイルコンテキスト:old_word of anarchism have often been divided into the categories of social and individualist anarchism or similar dual classifications
: はここに私のpython(だけ更新1回)のコードである 'の
cluster_labels: '[1、2]'
更新後: ターゲット・ファイル・コンテキスト:第2の更新用of_1 anarchism have often been divided into the categories of_2 social and individualist anarchism or similar dual classifications
:
old_word: 'アナキズム'
cluster_labels: '[1、2]'
更新後:
対象ファイルのコンテキスト:of_1 anarchism_1 have often been divided into the categories of_2 social and individualist anarchism_2 or similar dual classifications
私のコードでは、関数を2回呼び出してファイルを2回コピーする必要がありますが、更新する必要がある単語が多すぎると、このメソッドはかなり時間がかかり、読み取り/書き込み/コピーが頻繁になります。
このように頻繁に読み書き/コピーすることなく優雅に対処できる方法はありますか?