簡體   English   中英

Python字典,其中包含每個鍵的值列表

[英]Python Dictionary with a list of values for each key

我有兩個不同的文本文件:一個包含單詞及其頻率的文件,如下所示:

word1<space>frequency

第二個是一個文件,該文件的開頭是一個單詞,后跟它的相關功能。 看起來像:

word1<tab>feature1<tab>feature2................

第二個文件中的每個單詞都可以具有任意數量的功能(在我的情況下,范圍為0-7)

對於文件1中的每個單詞,我都希望從文件2中獲得與其相關的所有功能。我想創建一個詞典,其中的鍵是文件1中的單詞,其對應值是從文件2中獲得的功能列表。

另外,我想要獨特的功能,並希望消除文件2中的重復項(我尚未實現它)。

我有以下代碼,但它只為文件1中的第一個單詞提供所需的輸出mydict確實包含文件1中的所有其他單詞,但它們沒有任何關聯的值。

mydict = dict()

with open('sample_word_freq_sorted.txt', 'r') as f1:
        data = f1.readlines()

with open('sample_features.txt', 'r') as f2:
        for item in data:
                root = item.split()[0]
                mylist = []
                for line in f2:
                        words = line.split()
                        if words[0] == root:
                                mylist.append(words[1:])
                mydict[root] = mylist

此外,每個鍵的值是不同的列表,而不僅僅是一個不是我想要的列表。 有人可以幫我解決我代碼中的錯誤嗎?

mydict = dict()

with open('sample_word_freq_sorted.txt', 'r') as f1:
        data = set([ line.split()[0] for line in f1])

with open('sample_features.txt', 'r') as f2:
        for line in f2:
            word = line.split(' ')[0].strip()
            if word in data:
               mydict[word] = mydict.get(word,[]) + line.split(' ')[1:]

我認為您最可靠的方法是使用熊貓並合並。

df1 = pd.read_csv('sample_word_freq_sorted.txt', delim_whitespace=True)
df2 = pd.read_csv('sample_features.txt', delimeter='\t')
df2 = df2.drop_duplicates()

df = df1.merge(df2, how='left', on='word')

顯然,需要針對未發布的數據位進行自定義,但這比嘗試自定義循環中的所有內容要容易得多。 它還可以輕松處理重復的問題。

這是否是正確的解決方案還取決於您要對結果執行的操作-在某些情況下,使字典版本正常工作可能會更好。

編輯:當您的數據沒有列標題時,您可以讓Pandas為其命名,該名稱將是從0開始的整數:

pd.read_csv(path, headers=None)

然后,您可以使用整數(例如df [0]將引用名為0的第一列)或在以后更改標頭,例如,通過直接分配給df.columns = ['foo', 'bar', baz']或您可以在加載中指定標題:

pd.read_csv(path, names=['foo', 'bar', baz'])

文件是一個迭代器,這意味着您只能對其進行一次迭代:

>>> x = (i for i in range(3)) #example iterator
>>> for line in x:
    print(line)

0
1
2
>>> for line in x: #second time produces no results.
    print(line)

>>> 

因此for line in f2:循環for line in f2:僅在首次使用時才產生值( for item in data:的第一次迭代f2 = f2.readlines()要解決此問題,您可以執行f2 = f2.readlines()以便有一個列表可以然后再遍歷一次,或者找到一種僅用f2迭代來構造字典的方法。

然后,您將獲得一個子列表列表,因為您將每個單詞列表.append()都添加到mylist ,而不是通過附加單詞.extend擴展,因此只需進行以下更改:

mylist.append(words[1:])

mylist.extend(words[1:])

應該解決您遇到的其他問題。


這似乎是一種情況,其中collections.defaultdict會派上用場,而不是遍歷文件多次為每個特定單詞添加項目,而dict將自動為每個新單詞創建空列表,這將使您可以像這樣編寫代碼:

import collections
mydict = collections.defaultdict(list)

with open('sample_features.txt', 'r') as f2:
    for line in f2:
        tmp = line.split()
        root = tmp[0]
        words = tmp[1:]
        #in python 3+ we can use this notation instead of the above three lines:
        #root, *words = line.split()
        mydict[root].extend(words)

盡管由於只想保留唯一的功能,所以使用set而不是list會更有意義,因為它們(按定義)僅包含唯一的元素,然后使用.extend而不是.update

import collections
mydict = collections.defaultdict(set)
   ....
        mydict[root].update(words)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM