python - ConfigNumParser值错误: invalid literal for int() with base 10: ''

标签 python parsing numpy scipy pyparsing

这段代码几乎完全是从 scipy.org cookbook recipe 输入的。我还没有注意到任何拼写错误,所以也许代码已经过时了?为什么此代码可以正确解析数字,但在 KeyWord() 和 QuotedString() 方法上却失败?

    #use the Regex element to rapidly detect strings representing numbers:
from re import VERBOSE
number = Regex(r"""
               [+-]?    #optional sign
               (
                    (?:\d+(?P<float1>\.\d*)?)    # match 2 or 2.02
                  |                              # or
                    (?P<float2>\.\d+)?            # match .02
               )
               (?P<float3>[Ee][+-]?\d+)?         #optional exponent
               """, flags=VERBOSE
               )
# a function to convert this string into python float or integer and set a
# parseAction to tell pyparsing to automatically convert a number when it finds
# one:
def convert_number(t):
        """Convert a string matching a number to a python number"""
        print "Converting " + str(t)

        if t.float1 or t.float2 or t.float3:
            return [float(t[0])]
        else:
            return [int(t[0])]
            #try:
            #    return [int(t[0])]
            #except:
            #    return t

number.setParseAction(convert_number)

#  create a list of element converting strings to python objects:
from numpy import NAN
pyvalue_list = [
                number,
                Keyword('True').setParseAction(replaceWith(True)),
                Keyword('False').setParseAction(replaceWith(False)),
                Keyword('NAN', caseless=True).setParseAction(replaceWith(NAN)),
                Keyword('None').setParseAction(replaceWith(None)),
                QuotedString('"""', multiline=True),
                QuotedString("'''", multiline=True),
                QuotedString('"'),
                QuotedString("'"),
                ]

pyvalue = MatchFirst( e.setWhitespaceChars(' \t\r') for e in pyvalue_list)

根据食谱,我的输出应该是:

>>> test2 = '''
>>>     1   2   3.0  0.3 .3  2e2  -.2e+2 +2.2256E-2
>>>     True False nan NAN None
>>>     "word" "two words"
>>>     """'more words', he said"""
>>> '''
>>> print pyValue.searchString(test2)
[[1], [2], [3.0], [0.29999999999999999], [0.29999999999999999], [200.0], [-20.0], [0.022256000000000001],
[True], [False], [nan], [nan], [None], ['word'], ['two words'], ["'more words', he said"]]

但是我得到 ValueError: invalidliteral for int() with base 10: '' 所以我添加了一条打印语句来帮助调试,这是终端 session :

    Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigNumParser as parser
>>> test2 = '''
...     1 2 3.0 0.3 .3 2e3 -.2e+2 +2.2256E-2
...     True False nan NAN None
...     "word" "two words"
...     """'more words', he daid"""
... '''
>>> print parser.pyvalue.searchString(test2)
Converting ['1']
Converting ['2']
Converting ['3.0']
Converting ['0.3']
Converting ['.3']
Converting ['2e3']
Converting ['-.2e+2']
Converting ['+2.2256E-2']
Converting ['']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\Lib\site-packages\pyparsing.py", line 1099, in searchString
    return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
  File "C:\Python27\Lib\site-packages\pyparsing.py", line 1036, in scanString
    nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
  File "C:\Python27\Lib\site-packages\pyparsing.py", line 871, in _parseNoCache
    loc,tokens = self.parseImpl( instring, preloc, doActions )
  File "C:\Python27\Lib\site-packages\pyparsing.py", line 2451, in parseImpl
    ret = e._parse( instring, loc, doActions )
  File "C:\Python27\Lib\site-packages\pyparsing.py", line 897, in _parseNoCache
    tokens = fn( instring, tokensStart, retTokens )
  File "C:\Python27\Lib\site-packages\pyparsing.py", line 660, in wrapper
    ret = func(*args[limit[0]:])
  File "ConfigNumParser.py", line 33, in convert_number
    return [int(t[0])]
ValueError: invalid literal for int() with base 10: ''

因此,在此处搜索了几个建议之后,我添加了您在上面的注释区域中看到的 try-catch。现在的结果是:

 Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ConfigNumParser as parser
>>> test2 = '''
...     1 2 3.0 0.3 .3 2e3 -.2e+2 +2.2256E-2
...     True False nan NAN None
...     "word" "two words"
...     """'more words', he daid"""
... '''
>>> print parser.pyvalue.searchString(test2)
Converting ['1']
Converting ['2']
Converting ['3.0']
Converting ['0.3']
Converting ['.3']
Converting ['2e3']
Converting ['-.2e+2']
Converting ['+2.2256E-2']
Converting ['']
Converting ['']
Converting ['']
<deleted 65+ more of these>
Converting ['']
Converting ['']
Converting ['']
[[1], [2], [3.0], [0.3], [0.3], [2000.0], [-20.0], [0.022256], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], ['']]
>>>

在我继续搜索和学习的同时,我认为将问题发布给专业人士会对我和其他人有所帮助。

问候, 比尔

最佳答案

I can't yet notice any typo's so

...哎呀...

(?P<float2>\.\d+)?  

应该是

(?P<float2>\.\d+)

这解决了它。

关于python - ConfigNumParser值错误: invalid literal for int() with base 10: '' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15011935/

相关文章:

python - 为什么在与列表相乘时将 float64 转换为 int?

python - 当传递给 "numpy.array"时,生成器不工作是一个错误吗?

python - 如何将字符串转换为其 Base-10 表示形式?

Python/Pygame 向量数学

javascript - 如何从 AJAX 调用中使用 jQuery 呈现 HTML

python - 如何访问 numpy 数组中索引满足某些条件的所有元素?

c# - 优雅的方式解析URL

json - 不显示选定的 JSON 数据

java - 我试图在 eclipse 上运行这个程序,但在控制台中出现这个错误

python - pandas 列值到行值