Ich schreibe eine Funktion, die eine Textdatei nur einmal aktualisieren kann, aber ich muss es wiederholt tun. Um zu vermeiden, dass eine temporäre Datei häufig in eine Zieldatei kopiert wird, möchte ich alle Wörter in einer Schleife nur einmal aktualisieren. Wie kann ich das tun? Hier ist mein Python-Code (aber nur einmal aktualisieren):Wie aktualisiert man eine Textdatei in einer Schleife in 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)
zum Beispiel:
zum ersten Update:
Quelldatei Kontexte: of anarchism have often been divided into the categories of social and individualist anarchism or similar dual classifications
old_word: 'von'
cluster_labels: '[1, 2]'
nach Update: Zieldatei Kontexte: of_1 anarchism have often been divided into the categories of_2 social and individualist anarchism or similar dual classifications
zum zweiten Update:
old_word: 'Anarchismus'
cluster_labels: '[1, 2]'
nach Update:
Zieldateikontexte: of_1 anarchism_1 have often been divided into the categories of_2 social and individualist anarchism_2 or similar dual classifications
In meinem Code muss ich die Funktion zweimal aufrufen und die Datei zweimal kopieren, aber wenn die Wörter, die aktualisiert werden müssen, zu viele sind, ist diese Methode definitiv zeitaufwendig und häufiges Lesen/Schreiben/Kopieren, was unfreundlich ist.
Gibt es also irgendeine Methode, die elegant damit umgehen kann, ohne häufig zu lesen/schreiben/kopieren?