2017-03-12 30 views
2

我想用pyparsing編寫一個解析所有字符串包含特殊單詞的程序。我寫了下面的代碼,但它不工作: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") 

我試圖解析句子與「天」字的特殊但在分析它有錯誤...

pyparsing.ParseException:預期「day」(at char 42),(line:1,col:43)

+1

的規則'sentence'消耗一切的字符串的結尾包括單詞 「天」 ... –

回答

1

定義word時使用負向前視;否則,word匹配daysentence將消耗它。

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'] 
+0

非常感謝。解決我的問題我想。 –

+0

使用結果名稱'first'和'last'的額外點可以輕鬆訪問輸出的這些部分。 OP的注意事項 - 可能希望使用'day = Keyword(「day」)'來定義'day',否則你還會匹配像'daybreak','days','daylight','daydream'這樣的詞的前導部分等 – PaulMcG

+0

@PaulMcGuire嗯,好點,更新。 'pyparsing'是我最喜歡的圖書館之一,很高興看到作者在支持它的SO上非常活躍:)。 –

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'] 
+0

感謝。但這不是我確切的問題。我在寫一個大項目,我正在使用pyparsing來解析書的腳註。並且沒有處理一些自由詞後的特殊詞的解析,我不能很好地使用pyparsing來處理不同類型的腳註。所以我需要一種方法來解決pyparsing不能通過python解決問題的問題。 –

相關問題