替换文字python中的单词



我有txt格式的书的文字。

如果specific_words_dict字典中包含一个单词,我想用Word_1替换该单词(用cat_1) cat。我写了此代码,但它不替换文件中的单词。

for filename in os.listdir(path):
    with open(path+"/"+filename,'r+') as textfile:
        for line in textfile:
            for word in line.split():
                if(specific_words_dict.get(word) is not None):
                    textfile.write(line.replace(word,word+"_1"))

我在做什么错?

不要同时读取并写入文件。它不会很好。我认为目前您正在附加到文件上(因此您的所有新行都将到达结束(。

如果文件不是太大(可能不会(,我会将整个内容读为RAM。然后,您可以在重写整个文件之前编辑行列表。效率不高,但很简单,而且起作用。

for filename in os.listdir(path):
    with open(os.path.join(path, filename)) as fr:
        lines = fr.read().splitlines()
    for index, line in enumerate(lines):
        for word in line.split():
            if specific_words_dict.get(word) is not None:
                lines[index] = line.replace(word, word + "_1")
    with open(os.path.join(path, filename), 'w') as fw:
        fw.writelines(lines)

在其他文件中写入此外,您可以检查您的单词是否在大写或dict中的较低案例中或较低的情况。这也许是为什么"替换"不起作用的原因。

for filename in os.listdir(path):
    with open(path+"/"+filename,'r+') as textfile, open(path+"/new_"+filename,'w') as textfile_new:
        for line in textfile:
            new_line = line
            for word in line.split():
                if(specific_words_dict.get(word) is not None):
                 new_line = new_line.replace(word,word+"_1")
            textfile_new.write(new_line)

最新更新