python制作词典_如何使用python从文本文件制作字典

1586010002-jmsa.png

My file looks like this:

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

...

I want to make a dictionary with key = the word (like 'aaien') and the value should be a list of the numbers that are next to it.

So it has to look this way:

{'aaien': ['12, 13, 39'], 'aan': ['10']}

This code doesn't seem to work.

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 shell gives this error: ValueError: need more than 1 value to unpack

thanks!

解决方案

You are splitting your line into a list of words, but only giving it one key and value.

This will work:

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:]

Note that you don't need to give .split() an argument; without arguments it'll both split on whitespace and strip the results for you. That saves you having to explicitly call .strip().

The alternative is to split only on the first whitespace:

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()

The second argument to .split() limits the number of splits made, guaranteeing that there at most 2 elements are returned, making it possible to unpack the values in the assignment to key and value.

Either method results in:

{'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']}

If you still see only one key and the rest of the file as the (split) value, your input file is using a non-standard line separator perhaps. Open the file with universal line ending support, by adding the U character to the mode:

with open('LIWC_words.txt', 'rU') as document:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值