-5
我有一个由单词组成的source.txt文件。每个词都在一个新的行中。创建多维词典来计算词的出现
apple
tree
bee
go
apple
see
我也有一个taget_words.txt文件,其中的单词也在一行中。
apple
bee
house
garden
eat
现在我必须搜索源文件中的每个目标单词。如果找到目标单词,例如苹果,目标词的字典条目以及前3个和后3个词中的每一个。在这个例子中的情况下,这将是
words_dict = {'apple':'tree', 'apple':'bee', 'apple':'go'}
如何我可以告诉通过创建和填充字典前和SOURCE_FILE入境后考虑这三个字蟒蛇? 我的想法是使用列表,但最好的代码应该是非常有效和快速的,因为这些文件由几百万字组成。我想,在列表中,计算非常缓慢。
from collections import defaultdict
words_occ = {}
defaultdict = defaultdict(words_occ)
with open('source.txt') as s_file, open('target_words.txt') as t_file:
for line in t_file:
keys = [line.split()]
lines = s_file.readlines()
for line in lines:
s_words = line.strip()
# if key is found in s_words
# look at the 1st, 2nd, 3rd word before and after
# create a key, value entry for each of them
后来,我都数不过来的每个键,值对的发生和号码添加到一个单独的字典,这就是为什么我开始用defaultdict。
我会很高兴有关上述代码的任何建议。
如果你完全不知道如何做到这一点,我可以建议阅读Python的词典吗?在这里看到:https://docs.python.org/3.5/tutorial/datastructures.html#dictionaries – MooingRawr
“..为单词苹果创建一个多维词典”。目前还不清楚(你)想要做什么。 – asherbar
你所描述的听起来不像一个“多维”字典,只是一个普通的字典。建议你从一个'for'循环开始,该循环读取文件的每一行,并逐渐建立你想要的结构。在那里,现在你知道如何开始! – martineau