独自の構文でより多くの柔軟性を持たせたい場合は、ここであなたが与えてくれたデータ定義のためのシンプルなパーサーです:
data = """\
a = [-vegetable, +fruit, +apple, -orange, -citrus]
o = [-vegetable, +fruit, -apple, +orange, +citrus]
t = [+vegetable, -fruit]"""
from pyparsing import Word, alphas, oneOf, Group, delimitedList
# a basic token for a word of alpha characters plus underscores
ident = Word(alphas + '_')
# define a token for leading '+' or '-', with parse action to convert to bool value
inclFlag = oneOf('+ -')
inclFlag.setParseAction(lambda t: t[0] == '+')
# define a feature as the combination of an inclFlag and a feature name
feature = Group(inclFlag('has') + ident('feature'))
# define a definition
defn = ident('name') + '=' + '[' + delimitedList(feature)('features') + ']'
# search through the input test data for defns, and print out the parsed data
# by name, and the associated features
defns = defn.searchString(data)
for d in defns:
print d.dump()
for f in d.features:
print f.dump(' ')
print
プリント:
['a', '=', '[', [False, 'vegetable'], [True, 'fruit'], [True, 'apple'], [False, 'orange'], [False, 'citrus'], ']']
- features: [[False, 'vegetable'], [True, 'fruit'], [True, 'apple'], [False, 'orange'], [False, 'citrus']]
- name: a
[False, 'vegetable']
- feature: vegetable
- has: False
[True, 'fruit']
- feature: fruit
- has: True
[True, 'apple']
- feature: apple
- has: True
[False, 'orange']
- feature: orange
- has: False
[False, 'citrus']
- feature: citrus
- has: False
['o', '=', '[', [False, 'vegetable'], [True, 'fruit'], [False, 'apple'], [True, 'orange'], [True, 'citrus'], ']']
- features: [[False, 'vegetable'], [True, 'fruit'], [False, 'apple'], [True, 'orange'], [True, 'citrus']]
- name: o
[False, 'vegetable']
- feature: vegetable
- has: False
[True, 'fruit']
- feature: fruit
- has: True
[False, 'apple']
- feature: apple
- has: False
[True, 'orange']
- feature: orange
- has: True
[True, 'citrus']
- feature: citrus
- has: True
['t', '=', '[', [True, 'vegetable'], [False, 'fruit'], ']']
- features: [[True, 'vegetable'], [False, 'fruit']]
- name: t
[True, 'vegetable']
- feature: vegetable
- has: True
[False, 'fruit']
- feature: fruit
- has: False
Pyparsingは、無関係な空白をスキップし、名前付き属性を使用して解析されたデータを返すなど、オーバーヘッドの多くを処理します。 pyparsing wiki(SimpleBool.py)のブール評価者、またはより完全なブール評価者パッケージbooleanoを調べてください。
自然言語のクエリを解析しない限り、NLTKは必要ありません。ブール式の解析は、任意のネストが許可されていても、ほとんどの解析技術ではかなり簡単です(ほとんどの場合はほとんどありません)。 – delnan
です。私は音韻拘束のランキングのための最適性理論的eval()関数を作ろうとしています。 – Pygmalion
't'が 'トマト'を表す場合、これは実際には少なくとも植物学的に言えばフルーツです。 http://oxforddictionaries.com/page/tomatofruitveg – PaulMcG