【问题标题】:python: replace words in file with words from other filepython:用其他文件中的单词替换文件中的单词
【发布时间】:2015-02-20 10:08:04
【问题描述】:

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

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

我知道如何用 python 的字符串替换功能替换文件中的单个单词,但是当单词列在不同的文件中时我不知道如何执行此操作。我尽了最大努力,但我无法理解如何使用字典/列表/元组。我对 python 比较陌生,直到现在我都使用来自互联网的示例进行管理,但这超出了我的能力范围。我得到了各种各样的错误,比如“不可散列的类型:列表”和“需要一个字符缓冲区对象”。 我尝试的最后一件事是最成功的,因为我没有收到任何错误,但也没有任何反应。这是代码。我敢肯定它很丑,但我希望它不是完全没有希望的。

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

我这样做的原因是因为我正在编写具有基于成分的索引的食谱,并且我不想要同时包含“胡萝卜”和“胡萝卜”的索引,而是想要更改“胡萝卜”放入“胡萝卜”中,以此类推所有其他成分。 非常感谢您朝正确的方向轻推!

【问题讨论】:

  • 一方面,您需要使用d[key] = [value] 来创建列表字典,而不是d[key] = value
  • 但不清楚为什么你有一个列表的字典;这不是正确的数据模型。一个简单的字符串字典就可以了。
  • 常规 replace 可能不适合此任务。假设您确实整理了 dict 内容,并且最终将文件中的所有“carrot”实例替换为“carrots”。但这也将用“carrotss”替换所有现有的“carrots”实例。 replace 不只是寻找完整的词来替换;它会很乐意替换部分单词。
  • 谢谢。 @Kevin,这不是问题。这是一个用 LaTex 制作的索引,其中每个条目都用感叹号分隔,所以我会搜索“!carrot!”并将其替换为“!carrots!”。 Tom I 对代码的第一部分进行了调整。不确定这是否是你的意思。如果没有,我会去谷歌搜索更多关于这个 dict 的内容..

标签: python csv str-replace


【解决方案1】:

首先,您从 'wo​​rd.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)

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

【讨论】:

  • 这似乎很有魅力!一次一行地作为整个文件。不过,还没有足够的声誉来对您的答案进行投票。我很放心。非常感谢。
【解决方案2】:

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

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

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)

【讨论】:

  • 我试过了,但只有 csv 文件中的最后一对单词在文本文件中被替换了。不知道哪里出错了。无论如何,感谢您的思考!
  • 顺便说一句,我不确定我为什么要制作字典,然后制作两个列表 :) 感谢您提及元组,我会确保阅读更多有关此主题的内容。跨度>
猜你喜欢
  • 1970-01-01
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多