2017-03-12 15 views
2

すべての文字列に特殊な単語が含まれているかどうかを解析するプログラムを作成しようとしています。私は、次のコードを書いたが、それが動作していません。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:期待します(行1、col 43)

+1

ルール... –

答えて

1

wordを定義するときには否定的な先読みを使用してください。そうでない場合、worddayと一致し、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 

出力: `単語 "日" を含む文字列の最後にすべてを消費しsentence`ため

['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

「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をうまく使うことができませんでした。だから私はpythonで解決しないpyparsingで問題を処理する方法が必要です。 –

関連する問題