如何合并和搜索重复值?

2024-06-01 01:35:04 发布

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

所以我有一堆文本文件,我要读它们,数每个单词,然后输出到不同的文件中,像这样:(word)(file)(amount)

word1 file1 5
word1 file2 3
word2 file1 2
word2 file3 5

然后我需要对它们进行排序,并合并所有缩略词,保存文件和金额,如下所示:

word1 file1:5 file2:3
word2 file1:2 file3:5

并使用两个单词的搜索函数来查找只包含两个搜索单词的文件名。你知道吗

word1 in file1 counted 5
word2 in file1 counted 2

我做排序,但仍然需要做合并和搜索:(


Tags: 文件in排序单词amountfile1file2word
1条回答
网友
1楼 · 发布于 2024-06-01 01:35:04

假设你已经完成了第一步(似乎是这样),那么你可以这样做:

#this is what you start with
words = [ ('word1', 'file1', 5),
    ('word1', 'file2', 3),
    ('word2', 'file1', 2),
    ('word2', 'file3', 5) ]

#grouped by words
simple = {}
for word, f, count in words:
    try: simple [word] [f] = count
    except: simple [word] = {f: count}

print (simple)

#find files which contain both w1 and w2
def findTwoWords (data, w1, w2):
    files1 = set (data [w1].keys () )
    files2 = set (data [w2].keys () )
    return files1 & files2

print ('"word1" and "word2" appear together in {}'.format (findTwoWords (simple, 'word1', 'word2') ) )

相关问题 更多 >