我正在尝试通过以下测试:

from pyparsing import Word, nums, StringStart, StringEnd
import pytest

def get_square_feet(string):
    area = Word(nums+",")("area").setParseAction(lambda s, l, t: [int(t[0].replace(',', ''))])
    expression = StringStart() + area + "sqft" + StringEnd()
    return expression.parseString(string).get("area")

def test_get_square_feet():
    assert get_square_feet("800 sqft") == 800
    assert get_square_feet("9,000 sqft") == 9000

def test_get_square_feet_with_prefix():
    assert get_square_feet("size: 12,000 sqft") is None

if __name__ == "__main__":
    pytest.main([__file__])


但是,第二次测试失败,因为它导致ParseError。相反,我想使用searchString,但是如果在parseString函数中用searchString替换get_square_feet,我也会收到一个错误,因为该函数返回None。有人可以向我指出这里有什么问题吗?

最佳答案

这是使用pyparsing的相应代码,捕获了ParseException:

from pyparsing import Word, nums, StringStart, StringEnd, ParseException

def get_square_feet(string):
    area = Word(nums+",")("area").setParseAction(lambda s, l, t: [int(t[0].replace(',', ''))])
    expression = StringStart() + area + "sqft" + StringEnd()
    try:
        return expression.parseString(string).get("area")
    except ParseException:
        return None

关于python - PyParsing的searchString与StringStart()和StringEnd(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47016013/

10-12 22:13