3

我对 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'])   
4

3 回答 3

2

用于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)

但是,如果您只是缩进获取长度,那么将所有这些行存储在列表中是没有意义的。

于 2013-06-17T03:43:11.010 回答
1

dict.get(key, 0)返回当前累计计数。如果 key 不在 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

于 2013-06-17T03:25:18.823 回答
1

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))
于 2013-06-17T03:44:40.483 回答