python: 用其他文件中的词替换文件中的词

python: replace words in file with words from other file

我有一个很大的文本文件,其中有一些我想替换的词。我将这些词放在一个 csv 文件中,因为我不断地添加和更改词并且不想将这些词放在 python 脚本本身中。每行是一个我要替换的词,后面是我要替换的词。像这样:

A_old,A_new
another word,another new word
something old,something new
hello,bye

我知道如何使用字符串替换功能替换 python 文件中的单个单词,但当这些单词列在不同的文件中时,我不知道如何执行此操作。我尽了最大努力,但我无法理解如何使用 dictionaries/lists/tuples。我是 python 的新手,直到现在我都使用来自互联网的示例进行管理,但这超出了我的能力范围。我遇到了各种错误,例如 'unhashable type: list' 和 'expected a character buffer object'。 我尝试的最后一件事是最成功的,因为我没有收到任何错误,但也没有任何反应。这是代码。我敢肯定它很丑,但我希望它不是完全没有希望。

reader = csv.reader(open('words.csv', 'r'))
d = {}
for row in reader:
    key, value = row
    d[key] = value

newwords = str(d.keys())
oldwords = str(d.values())

with open('new.txt', 'wt') as outfile:
    with open('old.txt', 'rt') as infile:
        for line in infile:
            outfile.write(line.replace(oldwords,newwords))

我这样做的原因是因为我正在编写一本包含基于成分的索引的食谱,我不想要同时包含 'carrot' 和 'carrots' 的索引,而是我想要将 'carrot' 更改为 'carrots',以此类推所有其他成分。 非常感谢您在正确方向上的推动!

在您的代码示例中,您将替换词对读入字典,然后读入两个包含键和值的列表。我不知道为什么。

我建议将替换词读入元组列表。

with open('words.csv', 'rb') as rep_words:
    rep_list = []
    for rep_line in rep_words:
        rep_list.append(tuple(rep_line.strip().split(',')))

然后您可以打开 old.txtnew.txt 文件并使用嵌套 for 循环执行替换

with open('old.txt', 'rb') as old_text:
    with open('new.txt', 'wb') as new_text:
        for read_line in old_text:
            new_line = read_line
            for old_word, new in rep_list:
                new_line = new_line.replace(old_word, new_word))
            new_text.write(new_line)

首先你从 'word.csv' 中列出一对 (old_word, new_word) :

old_new = [i.strip().split(',') for i in open('words.csv')]

然后,您可以逐行替换:

with open('new.txt', 'w') as outfile, open('old.txt') as infile:
    for line in infile:
        for oldword, newword in old_new:
            line = line.replace(oldword, newword)
        outfile.write(line)

或一次在整个文件中:

with open('new.txt', 'w') as outfile, open('old.txt') as infile:
    txt = infile.read()
    for oldword, newword in old_new:
        txt = txt.replace(oldword, newword)    
    outfile.write(txt)

但您必须一次替换一个单词。