Python 分割函数。解包错误的值太多

标签 python string

我有一个 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's comment , 你可以像这样使用 partition 函数

url, _, count = data.partition(" ")

如果有一个以上的空格/没有空格,那么 count 将分别保存剩余的字符串或空字符串。

如果您使用的是 Python 3.x,您可以这样做

first, second, *rest = data.split()

在 Python 3 中,前两个值将分别分配给 firstsecond,列表的其余部分将分配给 rest .x

关于Python 分割函数。解包错误的值太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21254645/

相关文章:

java - 根据 Java 中的预定义模式验证字符串

string - Swift 和 XCode 6 - 将整数转换为字符串

python - 使用Python进行并行计算

python - 将 numpy 加载到 IronPython 中

python - 在排序的、固定大小的列表/python 中运行前 k 个元素

python - 多索引中的移位时间合并

python 排序列表列表与决胜局

java - 在Java中将 float 转换为字符串和字符串以 float

Python:将字符串中的字符替换为另一个字符串中的等效字符

python - 如何将一个字符与 Python 中某个字符串中的所有字符进行比较?