【发布时间】:2023-03-19 11:00:01
【问题描述】:
我有一个文件作为字典词:
water=45
melon=8
apple=35
pineapple=67
I=43
to=90
eat=12
tastes=100
sweet=21
it=80
watermelon=98
want=70
juice=88
我还有另一个文件,其中包含以下文本:
I want to eat banana and watermelon
I want drink juice purple and pineapple
我要输出:
43, 70, 90, 12, 98
43, 70, 88, 67
字典中不存在的每个单词都在skip中。
这是我目前所拥有的:
import re
f = open(r'C:\Users\dinesh_pundkar\Desktop\val.txt','r')
val_dict = {}
for line in f:
k, v = line.strip().split('=')
val_dict[k.strip()] = v.strip()
f.close()
h = open(r'C:\Users\dinesh_pundkar\Desktop\str_txt.txt','r')
str_list = []
for line in h:
str_list.append(str(line).strip())
tmp_str = ''
for val in str_list:
tmp_str = val
for k in val_dict.keys():
if k in val:
replace_str = str(val_dict[k]).strip() + ","
tmp_str= re.sub(r'\b{0}\b'.format(k),replace_str,tmp_str,flags=re.IGNORECASE)
tmp_str = tmp_str.strip(",")
print val, " = ", tmp_str
tmp_str = ''
输出:
43, 70, 90, 12, banana and 98
43, 70, drink 88, purple and 67
【问题讨论】:
标签: python python-2.7 python-3.x dictionary