[英]How to Replace value of string in file with dictionary key-value using python script
如何使用 python 用字典值替換文件中的字符串:
我有一個內容如下的文件:
No.of documents inserted in collection{col_id="feed-496"} 580
No.of documents inserted in collection{col_id="feed-497"} 620
No.of documents inserted in collection{col_id="feed-498"} 630
現在我有一本字典如下:
dict1={'feed-496':'high','feed-497':'low','feed-498':'medium'}
如何使用 python 腳本將文件中的 'feed-496' 替換為上述字典中的鍵值。
內置方法:
# file_contents = file.read() or similar, as long as it's a string.
for find, replacement in dict1.items():
file_contents.replace(find, replacement)
請注意,這種情況下的替換不應該也出現在字典鍵中,否則它們最終將被循環的后續迭代替換。
或者,使用正則表達式:
import re
# ...
# Make a function that picks what to replace with.
def feed_level(match_obj):
# Use the capture group (see regex below) as key for the dictionary.
return dict1[match_obj.group(0)]
re.sub(r'col_id="(.*?)"', feed_level, file_contents)
這與上述其他方法沒有相同的限制。 這兩種可能性都允許您隨時擴展字典,而無需在執行此代碼時修改此代碼。
要替換文本文件中的某些字符串,請使用 .replace(wrongelement, rightelement)
在.txt:
您好,歡迎來到 pyton。
代碼:
fin = open("in.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
輸出.txt:
你好,歡迎來到 python。
您的代碼將如下所示:
dict1={'feed-496':'high','feed-497':'low','feed-498':'medium'}
fin = open("in.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
for key in dict1:
fout.write(line.replace(key, dict1[key]))
fin.close()
fout.close()
使用正則表達式。
前任:
import re
dict1={'feed-496':'high','feed-497':'low','feed-498':'medium'}
with open(filename) as infile:
for line in infile: #Iterate Each Line
key = re.search(r'\"(.*?)\"', line) #Search for key between Quotes
if key:
print(line.replace(key.group(1), dict1.get(key.group(1), key.group(1)))) #Replace Value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.