简体   繁体   English

Python:如何从以单词为键、文件名为值的文件列表构建单词字典?

[英]Python: how to build a dictionary of words from a list of files with words as keys and file names as values?

I have a list of words that I have extracted from several files, and I need to build a dictionary such that the word would be a key corresponding to a list of filenames in which the word appears (can be more than one) as its value.我有一个从多个文件中提取的单词列表,我需要构建一个字典,以便该单词是对应于文件名列表的键,其中该单词出现(可以是多个)作为其值.

I have already got code to extract all the words from the files and remove spaces, commas etc. So it is a list of words.我已经有了从文件中提取所有单词并删除空格、逗号等的代码。所以它是一个单词列表。

The output should look something like this: output 应如下所示:

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

How can I achieve that?我怎样才能做到这一点?

I guess you want something like this.我猜你想要这样的东西。

Note: This python script file must be located in the same location as the txt files.注意:此 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)

Hope this works希望这有效

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 以句子的单词为键,从 1 开始的单词的 position 的个数作为 python 中的值构建字典 - Build a dictionary with the words of a sentence as keys and the number of position of the words from 1 as values in python 如何从字典中获取单词列表的值? - how to get values from a dictionary for a list of words? 如何快速从键列表和列表值构建python字典? - How to build a python dictionary from a list of keys and a list values, quickly? 使用单词列表python删除字典中的值 - Removing values in Dictionary with a list of words python 如何从特定词典关键字的值列表中删除单词? - How to remove words from list of values in specific dictionary key? Python根据键列表构建一个字典,并列出值列表 - Python build one dictionary from a list of keys, and a list of lists of values Python:如何从公司名称中删除常用词列表? - Python: How to remove a list of common words from company names? Python函数获取文本文件并创建以键为单词和值作为频率的字典 - Python function to take text file and create dictionary with keys as words and values as frequencies 如何将文本文件中的单词放入python字典中 - how to put the words in the text file into dictionary in python 如何将单词保存为具有任意 integer 值的字典键? - How to save words as dictionary keys with arbitrary integer values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM