csv Python - split()生成ValueError [duplicate]

l5tcr1uw  于 12个月前  发布在  Python
关注(0)|答案(5)|浏览(98)

此问题已在此处有答案

Why do I get a ValueError when trying to split a line of input and assign to multiple variables?(4个答案)
Split Strings into words with multiple word boundary delimiters(31个回答)
上个月关门了。
我试着把线分开:
American plaice - 11,000 lbs @ 35 cents or trade for SNE stocks
在字or,但我收到ValueError: not enough values to unpack (expected 2, got 1)
这是没有意义的,如果我在or处分割句子,那么确实会留下2条边,而不是1条。
下面是我的代码:

if ('-' in line) and ('lbs' in line):
    fish, remainder = line.split('-') 
    if 'trade' in remainder:
        weight, price = remainder.split('to ')
        weight, price = remainder.split('or')

'to'行是我通常使用的,它工作得很好,但是这个新行没有出现'to',而是出现了'or',所以我试着写一行来解决这两种情况,但无法解决,所以我只是写了第二行,现在遇到了上面列出的错误。
任何帮助都是感激的,谢谢。

sauutmhj

sauutmhj1#

最直接的方法可能是使用正则表达式进行拆分。然后你可以在任何一个词上分裂,无论出现什么。括号内的?:使组不捕获,这样匹配的单词就不会出现在输出中。

import re
# ...
weight, price = re.split(" (?:or|to) ", remainder, maxsplit=1)
6yt4nkrj

6yt4nkrj2#

在尝试在'or'上进行拆分之前,先在'to '上进行拆分,这会抛出错误。remainder.split('to ')的返回值是[' 11,000 lbs @ 35 cents or trade for SNE stocks'],它不能解压缩为两个单独的值。你可以通过测试你需要首先拆分哪个单词来解决这个问题。

if ('-' in line) and ('lbs' in line):
    fish, remainder = line.split('-') 
    if 'trade' in remainder:
        if 'to ' in remainder:
            weight, price = remainder.split('to ')
        elif ' or ' in remainder:
            weight, price = remainder.split(' or ') #add spaces so we don't match 'for'
lb3vh1jj

lb3vh1jj3#

这应该可以解决你的问题,首先检查你的分隔符是否在字符串中。
还要注意,split(str, 1)确保您的列表最多拆分一次(例如"hello all world".split(" ", 1) == ["hello", "all world"]

if ('-' in line) and ('lbs' in line):
    fish, remainder = line.split('-') 
    if 'trade' in remainder:
        weight, price = remainder.split(' to ', 1) if ' to ' in remainder else remainder.split(' or ', 1)
disho6za

disho6za4#

问题是,单词“for”也包含一个“or”,因此您将得到以下结果:

a = 'American plaice - 11,000 lbs @ 35 cents or trade for SNE stocks'
a.split('or')

['American plaice - 11,000 lbs @ 35 cents ', ' trade f', ' SNE stocks']

斯蒂芬·劳赫的回答确实解决了这个问题

fivyi3re

fivyi3re5#

完成split()之后,您就得到了一个列表,而不是一个字符串。所以你不能做另一个split()。如果你只是复制这一行,那么你将覆盖你的其他结果。您可以尝试将其作为字符串进行处理:

weight, price = remainder.replace('or ', 'to ').split('to ')

相关问题