简体   繁体   中英

search for a word in file and replace it with the corresponding value from dictionary in python

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM