Python split()生成ValueE

2024-10-03 17:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着分道扬镳:

American plaice - 11,000 lbs @ 35 cents or trade for SNE stocks

在单词or但我收到ValueError: not enough values to unpack (expected 2, got 1)。你知道吗

这是没有意义的,如果我在or处把句子分开,那么实际上会留下两个边,而不是一个。你知道吗

这是我的密码:

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',所以我试着写一行来处理这两种情况,但是没有弄清楚,所以我只写了第二行,现在遇到了上面列出的错误。你知道吗

谢谢您的帮助。你知道吗


Tags: ortoinforiflinepricesplit
3条回答

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

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

在尝试在'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'

这应该通过先检查字符串中是否有分隔符来解决问题。你知道吗

还要注意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)

相关问题 更多 >