我有一些关于 Defaultdict 和 Counter 的问题。我有一个文本文件,每行一个句子。我想把句子分成两部分(在第一个空格处)并将它们存储到一个字典中,第一个子字符串作为键,第二个子字符串作为值。这样做的原因是我可以获得共享相同 key 的句子总数。
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)
但是如果您只是缩进长度,那么将所有这些行存储在一个列表中是没有意义的。
关于python - 将一个句子分成两部分并将它们作为 Python 中的键和值存储到 defaultdict 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139954/