python - 读取文件并将其拆分为字典

标签 python python-2.7 dictionary io split

我有一个文件,我的数据如下:

1 [0,1, 4, 89]     
2 [3, 56, 6]     
3 [3,4,0]

等等。

我想读取这个文件以在我的脚本中逐行访问数据,所以我尝试这个来读取我的文件并将其记住在字典中:

dictionary = {}

with open('file.txt') as f:
    for line in f:
        nb, list = line.split(' ')
        dictionary[nb] = list 

然后我会做类似的事情:

for e in dictionary:
    etc.

我有这个错误:

too many values to unpack

因为我不知道如何处理列表中的第二个拆分元素。

是否有其他方法可以轻松访问和处理任何输入文件?

最佳答案

首先,您可以设置 str.split()maxsplit 参数.来自文档:

str.split(sep=None, maxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

演示:

>>> s = '1 [0,1, 4, 89]'
>>> s.split(' ', 1)
['1', '[0,1, 4, 89]']
>>> s.split(' ')
['1', '[0,1,', '4,', '89]']

>>> s.split(' ')[1]
'[0,1,'
>>> s.split(' ', 1)[1]
'[0,1, 4, 89]'

然后您需要将列表字符串 转换为真正的列表。我建议使用 ast.literal_eval() .来自文档:

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

例如:

>>> import ast
>>> s = '1 [0,1, 4, 89]'
>>> s.split(' ', 1)[1]
'[0,1, 4, 89]'
>>> ast.literal_eval(s.split(' ', 1)[1])
[0, 1, 4, 89]
>>> type(ast.literal_eval(s.split(' ', 1)[1]))
<class 'list'>
>>> type(s.split(' ', 1)[1])
<class 'str'>

如果您需要删除字符串后面的\n,只需使用str.strip() .来自文档:

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

像这样使用它:

>>> '   1 [0,1, 4, 89]   '.strip()
'1 [0,1, 4, 89]'
>>> '1 [0,1, 4, 89]\n'.strip()
'1 [0,1, 4, 89]'
>>> 

它删除了字符串前后的所有制表符、换行符、空格,如果你只想删除字符串前后的空格、换行符,请查看str.lstrip()。和 str.rstrip() .


所以你可以这样写你的代码:

import ast
dictionary = {}

with open('file.txt') as f:
    for line in f:
        key, value = line.strip().split(1)
        dictionary[key] = value

如果你想dictionary的键是int对象,只需使用int()函数来转换它,像这样:

import ast
dictionary = {}

with open('file.txt') as f:
    for line in f:
        key, value = line.strip().split(' ', 1)
        dictionary[int(key)] = value

关于python - 读取文件并将其拆分为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653936/

相关文章:

python - 如何从 Python 脚本列出 Gnu/Linux 上所有打开的 (X11) 窗口?

python - 从具有不同长度的列表生成数据框

java - 如何在 Robot Framework 中调用基于 Java 和 Python 的库?

Python:在列表字典中对列表进行排序,其中一个列表是排序的关键

Swift - 从字典中删除键和值 [String : Any]

python - 在 Apache/mod_wsgi 上运行 Django 时出错

python - 为什么 Popen ('ping URL' ).communicate() 在 Windows 中有效而在 Ubuntu 中无效?

python - 使用编码打开内存映射文件

python-2.7 - 如何计算骰子系数以测量python中图像分割的准确性

C++ 无序_Map : Receiving "error: expected unqualified-id before ‘[’ token"at Compile