簡體   English   中英

將一個句子拆分為兩個並將它們存儲為defaultdict作為Python中的鍵和值

[英]Splitting a sentence into two and storing them into a defaultdict as key and value in Python

我對Defaultdict和Counter有一些疑問。 我有一種情況,我有一個文本文件,每行一個句子。 我想將句子分成兩個(在第一個空格處)並將它們存儲到字典中,第一個子字符串作為鍵,第二個子字符串作為值。 這樣做的原因是我可以獲得共享相同密鑰的句子總數。

Text file format:
d1 This is an example
id3 Hello World
id1 This is also an example
id4 Hello Hello World
.
.

這是我嘗試過但它不起作用。 我看過Counter,但在我的情況下有點棘手。

try:
    openFileObject = open('test.txt', "r")
    try:             

        with openFileObject as infile:
            for line in infile:

                #Break up line into two strings at first space                    
                tempLine = line.split(' ' , 1)

                classDict = defaultdict(tempLine)         
                for tempLine[0], tempLine[1] in tempLine: 
                    classDict[tempLine[0]].append(tempLine[1]) 

            #Get the total number of keys  
            len(classDict)

            #Get value for key id1 (should return 2) 

    finally:
        print 'Done.'
        openFileObject.close()
except IOError:
    pass

在嘗試使用Counter或defaultdict之前,有沒有辦法在不拆分句子並將它們作為元組存儲在一個巨大的列表中的情況下執行此操作? 謝謝!

編輯:感謝所有回答的人。 我終於找到了我在這里出錯的地方。 我編寫了該程序,並提供了所有人給出的建議。

openFileObject = open(filename, "r")           
tempList = []

with openFileObject as infile:
    for line in infile:

        tempLine = line.split(' ' , 1)
        tempList.append(tempLine) 

        classDict = defaultdict(list) #My error is here where I used tempLine instead if list
        for key, value in tempList: 
            classDict[key].append(value)   

            print len(classDict) 
            print len(classDict['key'])   

使用collections.Counter “獲得共享相同鍵的句子總數。”

from collections import Counter
with openFileObject as infile:
    print Counter(x.split()[0] for x in infile)

將打印

Counter({'id1': 2, 'id4': 1, 'id3': 1})

如果你想存儲所有行的列表,那么你的主要錯誤就在這里

classDict = defaultdict(tempLine)

對於這種模式,您應該使用

classDict = defaultdict(list)

但是,如果你只是在縮短長度,那么將所有這些行存儲在列表中就沒有意義了。

dict.get(key, 0)返回當前累計計數。 如果密鑰不在dict中,則返回0。

classDict = {}

with open('text.txt') as infile:
    for line in infile:
        key = line.split(' ' , 1)[0]
        classDict[key] = classDict.get(key, 0) + 1

    print(len(classDict))
    for key in classDict:
        print('{}: {}'.format(key, classDict[key]))

http://docs.python.org/3/library/stdtypes.html#dict.get

defaultdict的完整示例(以及顯示classDict的改進方式)

from collections import defaultdict

classDict = defaultdict(int)

with open('text.txt') as f:
    for line in f:
        first_word = line.split()[0]
        classDict[first_word] += 1

    print(len(classDict))
    for key, value in classDict.iteritems():
        print('{}: {}'.format(key, value))

暫無
暫無

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

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