如何使用python从文本文件制作字典 [英] How to make a dictionary from a text file with python

查看:697
本文介绍了如何使用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
...

我想用一个key =该单词(如aaien)来创建一个字典,该值应该是它旁边的数字的列表。
所以它必须这样看:
{'aaien':['12,13,39'],'aan':['10']}



此代码似乎不起作用。

  document = open('LIWC_words.txt',' r')
liwcwords = document.read()
dictliwc = {}
在liwcwords中的行:
k,v = line.strip()。split('')
答案[k.strip()] = v.strip()

liwcwords.close()

python shell提供了这个错误:ValueError:需要多于1个值来解压缩



谢谢!

解决方案

你将你的行分成一个单词列表,但只给它一个键和值。



这将工作:

  with open('LIWC_words.txt','r')as document:
answer = {}
在文档中的行:
line = line.split()
如果不是行:#空行?
继续
答案[line [0]] =行[1:]

请注意,您不需要给出 .split()参数;没有争议,它将会分开空格并剥离您的结果。这样可以节省您明确调用 .strip()



替代方案是仅在第一个空格:


  with open('LIWC_words.txt','r')as document:
answer = {}
在文件中的行:
如果line.strip():#非空行?
key,value = line.split(None,1)#None表示'all whitespace',默认
answer [key] = value.split()

.split()的第二个参数限制了分割次数,保证了返回最多2个元素,可以将作业中的值解压缩到。 p>

任一方法都会导致:

  {'aaien':['12 ','13','39'],
'aan':['10'],
'aanbad':['12','13','14' '58','38'],
'aanbaden':['12','13','14','57','58','38'],
'aanbeden' :['12','13','14','57','58','38'],
'aanbid':['12','13','14' ','58','39'],
'aanbidden':['12','13','14','57','58','39'],
' aanbidt':[ '12','13','14','57','58','39'],
'aanblik':['27','28'],
'aanbreken' :['39']}

如果您仍然只看到一个键并且文件的其余部分作为(split)值,您的输入文件可能正在使用非标准行分隔符。使用通用行结束支持打开文件,通过添加 U 字符到模式:

  with open('LIWC_words.txt' ,'rU')作为文件:


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:

这篇关于如何使用python从文本文件制作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆