![](/img/trans.png)
[英]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
[英]Python: how to build a dictionary of words from a list of files with words as keys and file names as values?
我有一个从多个文件中提取的单词列表,我需要构建一个字典,以便该单词是对应于文件名列表的键,其中该单词出现(可以是多个)作为其值.
我已经有了从文件中提取所有单词并删除空格、逗号等的代码。所以它是一个单词列表。
output 应如下所示:
{'on': ['file1.txt'], 'got': ['file1.txt'],'hello': ['file1.txt'],'a': ['file1.txt', 'file2.txt'], 'bad': ['file1.txt', 'file2.txt']}
我怎样才能做到这一点?
我猜你想要这样的东西。
注意:此 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)
希望这有效
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.