首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >句法分析:解析带有特殊单词的句子。

句法分析:解析带有特殊单词的句子。
EN

Stack Overflow用户
提问于 2017-03-12 10:29:23
回答 2查看 942关注 0票数 2

我正在尝试编写一个程序,其中包含有特殊单词的所有字符串的解析。我编写了以下代码,但它不起作用:

代码语言:javascript
复制
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)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-12 15:43:32

在定义word时使用负前瞻性;否则,wordday匹配,sentence将使用它。

代码语言:javascript
复制
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

输出:

代码语言:javascript
复制
['hi', 'this', 'is', 'a', 'nice']
['and', 'everything', 'is', 'ok']
['hi', 'this', 'is', 'a', 'nice', 'day', 'and', 'everything', 'is', 'ok']
票数 2
EN

Stack Overflow用户

发布于 2017-03-12 13:14:10

throwing语法分析是抛出异常,因为它将"day“视为句子中的单词。

在本例中,您可以使用python内置模块字符串函数。

代码语言:javascript
复制
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']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42746287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档