【问题标题】:Python - split() producing ValueErrorPython - split() 产生 ValueError
【发布时间】:2017-03-24 17:41:49
【问题描述】:

我正在尝试拆分线路:

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',所以我尝试写一行来解决这两种情况但不能想不通,所以我只是写了第二个,现在遇到了上面列出的错误。

感谢任何帮助,谢谢。

【问题讨论】:

  • 那行没有'to '
  • 我知道,这就是为什么我在它下面添加了 'or'.... 这是它失败的行,即使我注释掉了 'to'
  • 我实际上有太多的东西要拆包.. 其余的分为 'or' 和 'for'
  • 您的错误是,当尝试首先在 'to ' 上拆分时,它返回一个长度为 1 的列表,无法将其解包为重量和价格

标签: python csv split


【解决方案1】:

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

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

【讨论】:

  • 哦,我没想到使用 RegEx 来做这件事会这么简单。运行那行代码虽然产生了一个语法错误,说keyword can't be an expression
【解决方案2】:

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

【讨论】:

  • 好的,我明白了。我不认为'or' 也会捕获'for',但这样做是有道理的。感谢帮助和解释,真的很清楚
  • @theprowler 我也错过了 if 语句中“或”的空格...见编辑
【解决方案3】:

这应该通过首先检查您的分隔符是否在字符串中来解决您的问题。

另请注意,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)

【讨论】:

    【解决方案4】:

    问题是“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']
    

    Stephen Rauch 的回答确实解决了问题

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

      • 你确定吗?因为在我的其余代码(我没有在上面添加)中,实际上我确实在没有错误的情况下进行了多次拆分......我是新手,我不是告诉你你错了,但我可以向您保证我的代码可以连续多次使用split()。另外,我尝试了您的代码行,但失败了:(它产生了ValueError: too many values to unpack (expected 2)
      • 如果要解压的东西太多,说明'to ''or '不止一个。
      猜你喜欢
      • 1970-01-01
      • 2018-12-30
      • 2013-07-05
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 2019-01-17
      相关资源
      最近更新 更多