我正在尝试编写一个程序,其中包含有特殊单词的所有字符串的解析。我编写了以下代码,但它不起作用:
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")我试着用特殊的词“天”来分析一个句子,但是它在分析的时候有错误.
pyparsing.ParseException:预期“日”(42号字符),(行:1,col:43)
发布于 2017-03-12 15:43:32
在定义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']发布于 2017-03-12 13:14:10
throwing语法分析是抛出异常,因为它将"day“视为句子中的单词。
在本例中,您可以使用python内置模块字符串函数。
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']https://stackoverflow.com/questions/42746287
复制相似问题