我正在尝试编写一个带有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:预期" day" (在char 42),(line:1,col:43)
答案 0 :(得分:1)
在定义sh
时使用否定前瞻;否则,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
答案 1 :(得分:0)
pyparsing正在抛出异常,因为它将“day”视为句子中的单词。
在这种情况下,您可以使用python内置模块string函数。
In [85]: str1 = "hi this is a nice day and everything is ok"
In [86]: str2 = "day"
In [87]: str2_pos = str1.find(str2)
In [88]: str1_split_str2 = [mystr[:str2_pos], mystr[str2_pos:str2_pos+len(str2)], mystr[str2_pos+len(str2):]]
In [89]: str1_split_str2
Out[89]: ['hi this is a nice ', 'day', ' and everything is ok']