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