![](/img/trans.png)
[英]Search for Word in Text file and replace with value from dictionary, only once
[英]search for a word in file and replace it with the corresponding value from dictionary in 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'
就地编辑文件很脏; 您最好写一个新文件,然后再替换旧文件。
您正在尝试将列表用作正则表达式,这是无效的。 我不确定为什么首先要使用正则表达式,因为这不是必需的。 您也不能将列表传递到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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.