使用Python中的dictionary从文本文件中提取单词(查找和替换)



我在一个文本文件中有以下几行:

some text
some text
fields: [orders.date, orders.collection, orders.cancelled, orders.location,
orders.arrival, orders.country, orders.delivered, orders.colors,
orders.complete_time, fight.cancelled, fligt.arrival, flight.delayed]
some text 
some text

我想替换'.'之后的每个单词,例如,orders.date现在应该是orders.Date_time_stamp。类似地,将orders.collection更改为orders.Collected_at由于这是一个txt文件,我不知道如何超越括号[],然后替换其中的每个单词。

我把这些单词存储在字典中,所以我使用for循环。关键在于老单词,价值在于新单词。例如,"date"是key,date_time_stamp是value.。类似地,集合是密钥,值是Collected_at

d = {
'date': 'Date_time_stamp', 
'collection':'collected_at'
# And so on...
}

有什么办法解决这个问题吗?

以下是如何使用for循环使程序在字典中迭代,并使用re.sub将每个键替换为相应的值:

import re
d = {'date': 'Date_time_stamp', 'collection':'collected_at'}
with open('text.txt', 'r') as f:
text = f.read()
for k in d:
text = re.sub(f'.{k}(?!w)', f'.{d[k]}', text)
with open('text.txt', 'w') as w:
w.write(text)

之前:

some text
some text
fields: [orders.date, orders.collection, orders.cancelled, orders.location,
orders.arrival, orders.country, orders.delivered, orders.colors,
orders.complete_time, fight.cancelled, fligt.arrival, flight.delayed]
some text 
some text

之后:

some text
some text
fields: [orders.Date_time_stamp, orders.collected_at, orders.cancelled, orders.location,
orders.arrival, orders.country, orders.delivered, orders.colors,
orders.complete_time, fight.cancelled, fligt.arrival, flight.delayed]
some text 
some text

最新更新