将字典中的键与文本文件中的数据进行匹配是最有效的方法 [英] What is the most efficient way to match keys from a dictionary to data in text file
本文介绍了将字典中的键与文本文件中的数据进行匹配是最有效的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
data = [a 1:A,b 2:B,c 3: C,d 4:D]
和一个.txt文件,内容如下:
键a 1 b 2 c 3 d 4
Word作为框牛挖
(笔记值由\\ TAB字符分隔)
我可以使用数据字典中的键从.txt文件中找到相应的单词吗?理想情况下,我想输出一个字典:
data = [a 1:as,b 2:box,c 3:牛,d 4:挖]
请询问更多信息。如果需要,
感谢,
Alex
解决方案
如下所示:
with open('abc')as f:
keys = map(str.strip,next(f).split('Key')[1] .split(''))
vals = map(str.strip,next(f).split ('Word')[1] .split('\t'))
print dict(zip(keys,vals))
...
{'d 4':'挖,'b 2':'box','a 1':'as','c 3':'cow'}
Say I have the following dictionary:
data=[a 1 : A, b 2 : B, c 3 : C, d 4 : D]
and a .txt file which reads:
Key a 1 b 2 c 3 d 4
Word as box cow dig
(note values are seperated by \t TAB character)
How can I use the keys from the data dictionary to find the corresponding word from the .txt file? Ideally I would like to output a dictionary like:
data=[a 1 : as, b 2 : box, c 3 : cow, d 4 : dig]
Please ask for more info. if needed.
Thanks,
Alex
解决方案
Something like this:
with open('abc') as f:
keys = map(str.strip, next(f).split('Key ')[1].split(' '))
vals = map(str.strip, next(f).split('Word ')[1].split('\t'))
print dict(zip(keys,vals))
...
{'d 4': 'dig', 'b 2': 'box', 'a 1': 'as', 'c 3': 'cow'}
这篇关于将字典中的键与文本文件中的数据进行匹配是最有效的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文