在嵌套字典中放入信息片段 (Python)

Putting in Pieces of Information in A Nested Dictionary (Python)

我正在尝试创建一个嵌套字典,告诉我每个单词出现在哪个文档中以及出现在哪个位置:例如:

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

我想要 print(dictionary['mario']) 给出 [{'file1.txt': [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()}

我不知道如何在我目前没有的嵌套词典中实现单词的位置!有人能帮忙吗?

你的一层嵌套太多了。您的第一个描述对应于一个字典,其键是单词,其值是 dictionaries of (filename, position_list) pairs(例如 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]}

我不确定最后一行是干什么用的,因为目前没有重复项;在任何情况下,不要使用 dict 作为 Python 中的变量名,因为它是内置的。