如何解决使用Python中的字典从文本文件中提取单词查找和替换
我在文本文件中包含以下几行:
Code is organized as ( Step 1,2,3 are SQL queries) :-
Step 1 query - input is raw data table
Step 2 query - input is output of Step 1 view
Step 3 query - input is output of Step 2 view
我想替换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
由于这是一个txt文件,因此我不确定如何超过括号orders.Collected_at
,然后替换其中的每个单词。
我把单词存储为字典,所以我使用for循环。关键是旧词,价值是新词。例如,“ date”是[]
,Date_time_stamp是key
。同样,集合是键,值是Collected_at
value.
有什么办法解决这个问题?
解决方法
以下是使用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,flight.delayed]
some text
some text
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。