簡體   English   中英

在文件中搜索一個單詞,並將其替換為python中字典中的相應值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM