在文件中搜索一个单词,并将其替换为python中字典中的相应值

时间:2019-01-20 03:52:30

标签: python

我想从某个文件中搜索一个单词,然后用与关键字词典不同的字符串替换该单词。基本上只是文本替换。

我下面的代码不起作用:

keyword = {
    "shortkey":"longer sentence",
  "gm":"goodmorning",
  "etc":"etcetera"

}

with open('find.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        if re.search(keyword.keys(), line):         
            file.write(line.replace(keyword.keys(), keyword.values()))
            break

我写print时的错误消息:

Traceback (most recent call last):
  File "py.py", line 42, in <module>
    if re.search(keyword.keys(), line):         
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
    return _compile(pattern, flags).search(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 237, in _compile
    p, loc = _cache[cachekey]
TypeError: unhashable type: 'list'

1 个答案:

答案 0 :(得分:2)

就地编辑文件很脏;您最好写一个新文件,然后再替换旧文件。

您正试图将列表用作正则表达式,这是无效的。我不确定为什么首先要使用正则表达式,因为这不是必需的。您也无法将列表传递到str.replace

您可以遍历关键字列表,并对照字符串检查每个关键字。

keyword = {
    "shortkey": "longer sentence",
    "gm": "goodmorning",
    "etc": "etcetera"
}

with open('find.txt', 'r') as file, open('find.txt.new', 'w+') as newfile:
    for line in file:
        for word, replacement in keyword.items():
            newfile.write(line.replace(word, replacement))

# Replace your old file afterwards with the new one
import os
os.rename('find.txt.new', 'find.txt')