创建多维字典以计算出现的单词数

2024-04-24 00:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个源.txt由单词组成的文件。每个单词都在一行中。你知道吗

apple
tree
bee
go
apple
see

我还有一个塔吉特_文字.txt文件中,每个单词也在一行中。你知道吗

apple
bee
house
garden
eat

现在我必须在源文件中搜索每个目标词。如果找到目标词,例如apple,则应为目标词以及前3个和后3个词中的每个词创建一个词典条目。在这个例子中,那就是

words_dict = {'apple':'tree', 'apple':'bee', 'apple':'go'}

如何通过创建和填充字典来告诉python在源文件中的条目前后考虑这3个单词? 我的想法是使用列表,但理想情况下,代码应该是非常有效和快速的,因为文件由数百万字组成。我想,使用列表,计算速度很慢。你知道吗

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。你知道吗

我将很高兴为上述代码的任何建议。你知道吗


Tags: 文件intxttreegoapple目标for
1条回答
网友
1楼 · 发布于 2024-04-24 00:09:26

你将面临的第一个问题是你缺乏对格言的理解。每个键只能出现一次,因此,如果您要求解释器提供您所提供的键的值,您可能会得到一个惊喜:

>>> {'apple':'tree', 'apple':'bee', 'apple':'go'}
{'apple': 'go'}

问题是只有一个值与键'apple'关联。你知道吗

您似乎正在搜索合适的数据结构,但StackOverflow是用来改进或修复有问题的代码的。你知道吗

相关问题 更多 >