【问题标题】:Replace word in text python替换文本python中的单词
【发布时间】:2018-07-22 12:52:39
【问题描述】:

我有一本txt格式的书。

如果 specific_words_dict 字典中包含一个词,我想用 word_1 替换那个词(catcat_1). 我写了这段代码,但它不会替换文件中的单词。

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"))

我做错了什么?

【问题讨论】:

    标签: python string text replace text-files


    【解决方案1】:

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

    如果文件不是太大 大(可能不会),我会将整个文件读入内存。然后您可以在重写整个文件之前编辑行列表。效率不高,但简单,而且有效。

    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)
    

    【讨论】:

    • 在第二个 for 循环下错过了 if 语句
    • @FHTMitchell 它有效,但我想在文本中替换字典中的每个单词,而不仅仅是一个。
    • 好点,我已经确定了我的答案。当您尝试编写代码而不运行它时会发生这种情况:p
    【解决方案2】:

    写入其他文件 此外,您可以检查您的单词在您的字典或文件中是大写还是小写。这可能是“替换”不起作用的原因。

    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)
    

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      相关资源
      最近更新 更多