如何用Python从文本文件创建字典
我的文件看起来是这样的:
aaien 12 13 39
aan 10
aanbad 12 13 14 57 58 38
aanbaden 12 13 14 57 58 38
aanbeden 12 13 14 57 58 38
aanbid 12 13 14 57 58 39
aanbidden 12 13 14 57 58 39
aanbidt 12 13 14 57 58 39
aanblik 27 28
aanbreken 39
...
我想创建一个字典,字典的键是单词(比如'aaien'),而值应该是一个与它相邻的数字列表。 所以它应该像这样: {'aaien': ['12, 13, 39'], 'aan': ['10']}
但是这段代码似乎不太管用。
document = open('LIWC_words.txt', 'r')
liwcwords = document.read()
dictliwc = {}
for line in liwcwords:
k, v = line.strip().split(' ')
answer[k.strip()] = v.strip()
liwcwords.close()
python给出了这个错误:
ValueError: need more than 1 value to unpack
2 个回答
2
>liwcwords = document.read()
>dictliwc = {}
>for line in liwcwords:
你现在是在遍历一个字符串,这样做不是你想要的。试试 document.readlines()
。这里还有另一种解决方案。
from pprint import pprint
with open('LIWC_words.txt') as fd:
d = {}
for i in fd:
entry = i.split()
if entry: d.update({entry[0]: entry[1:]})
pprint(d)
这是输出的样子
{'aaien': ['12', '13', '39'],
'aan': ['10'],
'aanbad': ['12', '13', '14', '57', '58', '38'],
'aanbaden': ['12', '13', '14', '57', '58', '38'],
'aanbeden': ['12', '13', '14', '57', '58', '38'],
'aanbid': ['12', '13', '14', '57', '58', '39'],
'aanbidden': ['12', '13', '14', '57', '58', '39'],
'aanbidt': ['12', '13', '14', '57', '58', '39'],
'aanblik': ['27', '28'],
'aanbreken': ['39']}
9
你正在把一行文字分成一个单词列表,但只给了一个键和一个值。
这样做是可以的:
with open('LIWC_words.txt', 'r') as document:
answer = {}
for line in document:
line = line.split()
if not line: # empty line?
continue
answer[line[0]] = line[1:]
注意,你不需要给 .split()
传递任何参数;如果不传参数,它会自动根据空格来分割,并且会帮你去掉结果两边的空格。这就省去了你需要单独调用 .strip()
的麻烦。
另一种方法是只在第一个空格处分割:
with open('LIWC_words.txt', 'r') as document:
answer = {}
for line in document:
if line.strip(): # non-empty line?
key, value = line.split(None, 1) # None means 'all whitespace', the default
answer[key] = value.split()
传给 .split()
的第二个参数限制了分割的次数,确保最多只返回两个元素,这样就可以把值分别赋给 key
和 value
。
无论哪种方法,结果都是:
{'aaien': ['12', '13', '39'],
'aan': ['10'],
'aanbad': ['12', '13', '14', '57', '58', '38'],
'aanbaden': ['12', '13', '14', '57', '58', '38'],
'aanbeden': ['12', '13', '14', '57', '58', '38'],
'aanbid': ['12', '13', '14', '57', '58', '39'],
'aanbidden': ['12', '13', '14', '57', '58', '39'],
'aanbidt': ['12', '13', '14', '57', '58', '39'],
'aanblik': ['27', '28'],
'aanbreken': ['39']}
如果你仍然只看到一个键,其他的内容都作为(分割后的)值,那可能是你的输入文件使用了非标准的行分隔符。你可以通过添加 U
字符到模式中,以支持 通用行结束符,来打开文件:
with open('LIWC_words.txt', 'rU') as document: