我正在尝试用 pyparsing 编写一个程序来解析所有包含特殊单词的字符串。我写了下面的代码,但它不起作用:
from pyparsing import *
word = Word(alphas)
sentence = OneOrMore(word)
day = Literal("day")
sentence_end_with_happy = sentence + day + sentence
ret = sentence_end_with_happy.parseString("hi this is a nice day and everything is ok")
我试图解析一个带有特殊单词“day”的句子,但在解析时出现错误...
pyparsing.ParseException: Expected "day" (at char 42), (line:1, col:43)
请您参考如下方法:
在定义 word 时使用否定前瞻;否则,word 匹配 day 并且 sentence 将使用它。
from pyparsing import *
day = Keyword("day")
word = ~day + Word(alphas)
sentence = OneOrMore(word)
sentence_end_with_happy = sentence('first') + day + sentence('last')
ret = sentence_end_with_happy.parseString("hi this is a nice day and everything is ok")
print ret['first']
print ret['last']
print ret
输出:
['hi', 'this', 'is', 'a', 'nice']
['and', 'everything', 'is', 'ok']
['hi', 'this', 'is', 'a', 'nice', 'day', 'and', 'everything', 'is', 'ok']
