我有一本 Python 字典,目前看起來像這樣:
{'apple': ['file1.txt', 'file2.txt', 'file3.txt'], 'banana': ['file1.txt', 'file2.txt'],
'carrot': ['file3.txt'],.....................................}
我將每個檔案的內容存盤在一個串列串列中,該串列包含來自該檔案的單詞以及所用檔案的一般串列:
[['hello', 'apple', 'test', 'banana'], ['weird', 'apple', 'tester', 'banana', 'apple'],........]]
['file1.txt', 'file2.txt', .....]
現在我想創建一個包含從以前的一個,但所有的資訊,新的嵌套的字典還,其中術語出現的每個檔案(如果該檔案中存在)的位置。
例如:我想print(dictionary['apple'])回傳[{'file1.txt': [1]}, {'file2.txt': [1,4]},...... ](它告訴我它出現在哪個檔案中以及它在該檔案中的位置)
我現有的用于創建我已經擁有的字典的代碼是:
dict = {}
for i in range(len(textfile_list)): #list of textfiles used
check = file_contents #contents of file in form [['word1',..],['word2','wordn',...]]
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()}
我該怎么做??
uj5u.com熱心網友回復:
我可以像下面這樣組織你的作業流程。將此作為靈感來源:
content = [['hello', 'apple', 'test', 'banana'], ['weird', 'apple', 'tester', 'banana', 'banana', 'apple']]
files = ['file1.txt', 'file2.txt']
index = {k:v for k, v in zip(files, content)}
words = set([word for words in index.values() for word in words])
expected_dict = {}
for word in words:
expected_dict[word]=[]
for key, value in index.items():
if word in value:
expected_dict[word].append({key:[idx for idx in range(len(value)) if value[idx]==word]})
輸出:
{'test': [{'file1.txt': [2]}],
'apple': [{'file1.txt': [1]}, {'file2.txt': [1, 5]}],
'banana': [{'file1.txt': [3]}, {'file2.txt': [3, 4]}],
'tester': [{'file2.txt': [2]}],
'hello': [{'file1.txt': [0]}],
'weird': [{'file2.txt': [0]}]}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/340164.html
