Reputation: 131
I want to search for a word from some file and replace that word with different string from the dictionary of keywords. It's basically just text replacement thing.
My code below doesn't work:
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
The error message when I write 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'
Upvotes: 0
Views: 1041
Reputation: 56
Editing a file in place is dirty; you would be better off writing to a new file, and, afterward, replacing your old file.
You are attempting to use a list as a regex, which isn't valid. I'm not sure why you are using regex in the first place, as it's not necessary. You also cannot pass a list into str.replace
.
You can iterate over the list of keywords and check each one against the string.
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')
Upvotes: 2