我正在尝试创建一个嵌套字典,告诉我每个单词出现在哪个文档中以及它出现在哪个位置:例如:
dictionary ={}
textfile_list = ['file1.txt', 'file2.txt', 'file3.txt']
file_contents = ['mario luigi friend mushroom', 'rick mario morty portal summer mario', 'peter griffin shop']
#first element corresponds to the contents of file1.txt and etc.
words = [['mario', 'luigi', 'friend', 'mushroom'],
['rick', 'mario', 'morty', 'portal', 'summer', 'mario'],
['peter', 'griffin', 'shop']] #tokenising the text
我想要打印(字典("马里奥"))给[{‘中’:[0]},{file2.txt: [1,5]}]
目前为止我的代码是:
dict = {}
for i in range(len(textfile_list)):
check = file_contents
for item in words: #a list of every word from every file ['word1','wordn','word3',...]
if item in check:
if item not in dict:
dict[item] = []
if item in dict:
dict[item].append(textfile_list[i])
dict = {k: list(set(v)) for k, v in dict.items()}
我不知道如何在嵌套字典中实现单词的位置,我现在没有!有人能帮忙吗?
您的嵌套层太多了。你的第一个描述对应于一个字典,它的键是单词,它的值是字典(filename, position_list)对(例如dictionary['mario'] = {'file1.txt': [0], 'file2.txt': [1, 5]}
),而不是一个字典,它的键是单词,它的值是一个字典的列表,每个字典有一个文件名,如你所做的。
textfile_list = ['file1.txt', 'file2.txt', 'file3.txt']
file_contents = ['mario luigi friend mushroom', 'rick mario morty portal summer mario',
'peter griffin shop']
# first element corresponds to the contents of file1.txt and etc.
# words = [string_list.split() for string_list in file_contents]
words = [['mario', 'luigi', 'friend', 'mushroom'],
['rick', 'mario', 'morty', 'portal', 'summer', 'mario'],
['peter', 'griffin', 'shop']] # tokenising the text
dictionary = {}
for textfile_name, file_strings in zip(textfile_list, words):
for position, word in enumerate(file_strings):
if word not in dictionary:
dictionary[word] = {}
if textfile_name not in dictionary[word]:
dictionary[word][textfile_name] = []
dictionary[word][textfile_name].append(position)
print(dictionary['mario'])
>>> {'file1.txt': [0], 'file2.txt': [1, 5]}
我不确定最后一行是什么,因为目前没有重复;在任何情况下,不要在Python中使用dict
作为变量名,因为它是内置的。