【问题标题】:Python: how to build a dictionary of words from a list of files with words as keys and file names as values?Python:如何从以单词为键、文件名为值的文件列表构建单词字典?
【发布时间】:2020-11-27 14:26:06
【问题描述】:

我有一个从多个文件中提取的单词列表,我需要构建一个字典,以便该单词成为与该单词出现的文件名列表相对应的键(可以是多个)作为它的值。

我已经得到了从文件中提取所有单词并删除空格、逗号等的代码。所以它是一个单词列表。

输出应该是这样的:

{'on': ['file1.txt'], 'got': ['file1.txt'],'hello': ['file1.txt'],'a': ['file1.txt', 'file2.txt'], 'bad': ['file1.txt', 'file2.txt']}

我怎样才能做到这一点?

【问题讨论】:

  • 遍历一个文件的所有单词,对于每个单词,将文件名添加到字典中的列表中,以单词为关键字。

标签: python file dictionary


【解决方案1】:

我猜你想要这样的东西。

注意:此 python 脚本文件必须与 txt 文件位于同一位置。


files = os.listdir()
txt_files = []
for file in files:
    if file.endswith('.txt'):
        txt_files.append(file)

words = dict()

for file in txt_files:
    with open(file,'r',encoding='utf-8') as file:
        word_list = file.readlines()
        words[str(file.name)] = word_list

print(words)

【讨论】:

    【解决方案2】:

    希望这可行

    import os
    
    wordLst = ['on', 'got','hello','a',
           'bad']
    
    dic = {}
    
    for word in wordLst:
        dic.update({word: []})
    
    path = r'yourPath'
    filelst = os.listdir(path)
    
    for file in filelst:
    
    if '.txt' not in file: continue
    
    f = open(path + '\\' + file, 'r')
    txt = f.readlines()
    
    for key in dic.keys():
        if key in txt:
            dic[key].append(file)
    

    【讨论】:

    • 顺便说一句,wordLst 对应于您拥有的单词列表,因此您必须将其替换为您的实际列表。您还需要在 path 变量中放置文本文件所在目录的路径
    猜你喜欢
    • 2019-07-03
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2021-07-23
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多