Python分割功能。太多值无法解包错误
问题内容:
我有一个python函数,必须从文件中读取数据并将其拆分为两个键和值,然后将其存储在字典中。示例:文件:
http://google.com 2
http://python.org 3
# and so on a lot of data
我为此使用了split函数,但是当确实有大量数据时,它将引发值错误
ValueError: too many values to unpack
我该怎么办?
这是失败的确切代码
with open(urls_file_path, "r") as f:
for line in f.readlines():
url, count = line.split()# fails here
url_dict[url] = int(count)
问题答案:
您试图将拆分列表解包为这两个变量。
url, count = line.split()
如果没有空间或两个或多个空间怎么办?其余的单词会去哪儿?
data = "abcd"
print data.split() # ['abcd']
data = "ab cd"
print data.split() # ['ab', 'cd']
data = "a b c d"
print data.split() # ['a', 'b', 'c', 'd']
您实际上可以在分配前检查长度
with open(urls_file_path, "r") as f:
for idx, line in enumerate(f, 1):
split_list = line.split()
if len(split_list) != 2:
raise ValueError("Line {}: '{}' has {} spaces, expected 1"
.format(idx, line.rstrip(), len(split_list) - 1))
else:
url, count = split_list
print url, count
使用输入文件,
http://google.com 2
http://python.org 3
http://python.org 4 Welcome
http://python.org 5
这个程序会产生
$ python Test.py
Read Data: http://google.com 2
Read Data: http://python.org 3
Traceback (most recent call last):
File "Test.py", line 6, in <module>
.format(idx, line.rstrip(), len(split_list) - 1))
ValueError: Line 3: 'http://python.org 4 Welcome' has 2 spaces, expected 1
在@abarnert的评论之后,您可以使用partition
像这样的函数
url, _, count = data.partition(" ")
如果有多个空格/没有空格,count
则将分别保留其余字符串或空字符串。
如果您使用的是Python 3.x,则 可以执行以下操作
first, second, *rest = data.split()
在Python 3.x中,前两个值将分别在first
和中分配,second
列表的其余部分将分配给rest
。