2013-07-15 3 views
1

저는 Python 3.2를 사용하고 문장을 생성하기 위해 무작위로 생성 된 구문 분석 트리를 만들려고했습니다. 문장을 생성한다고 확신하지만, 구문 분석이 얼마나 무작위인지는 잘 모르겠습니다. 트리는 또한이 코드를 개선하는 더 나은/효율적인 방법이 있는지 모르겠습니다. 는 (I는 다음과 같은 프로그래밍 및 파이썬에 새로운 오전 나는 최근 NLP에 관심이 있었다. 어떤 조언, 솔루션 또는 수정을 환영합니다.)수정 된 어휘 집합을 사용하여 무작위로 생성 된 구문 분석 트리

N=['man','dog','cat','telescope','park'] #noun 
P=['in','on','by','with'] #preposition 
det=['a','an','the','my'] #determinant 
V=['saw','ate','walked'] #verb 
NP=['John','Mary','Bob'] #noun phrase 


from random import choice 
PP=choice(NP)+' '+choice(P) #preposition phrase 
PP=''.join(PP) 
VP=''.join(choice(V)+' '+choice(NP)) or''.join(choice(V)+' '.choice(NP)+(PP)) #verb phrase   
VP=''.join(VP) #verb phrase 
S=choice(NP)+' '+VP #sentence 
print(S) 
+0

http://nltk.org/book/ch08.html [올바른 장소 귀하의 질문에 대한 : 코드 검토] (http://codereview.stackexchange.com/?as=1) –

+0

나는 코드 검토에 대한 내 질문에 태그를 추가했습니다. – RamyaV

+0

http://codereview.stackexchange.com/?as=1 –

답변

2

가 NLTK를 시도

import nltk 
from random import choice, shuffle, random 

# Sometimes i find reading terminals as values into a dict of POS helps. 
vocab={ 
'Det':['a','an','the','my'], 
'N':['man','dog','cat','telescope','park'], 
'V':['saw','ate','walked'], 
'P':['in','on','by','with'], 
'NP':['John','Mary','Bob'] 
} 

vocab2string = [pos + " -> '" + "' | '".join(vocab[pos])+"'" for pos in vocab] 

# Rules are simpler to be manually crafted so i left them in strings 
rules = ''' 
S -> NP VP 
VP -> V NP 
VP -> V NP PP 
PP -> NP P 
NP -> Det N 
''' 

mygrammar = rules + "\n".join(vocab2string) 
grammar = nltk.parse_cfg(mygrammar) # Loaded your grammar 
parser = nltk.ChartParser(grammar) # Loaded grammar into a parser 

# Randomly select one terminal from each POS, based on infinite monkey theorem, i.e. selection of words without grammatical order, see https://en.wikipedia.org/wiki/Infinite_monkey_theorem 
words = [choice(vocab[pos]) for pos in vocab if pos != 'P'] # without PP 
words = [choice(vocab[pos]) for pos in vocab] + choice(vocab('NP')) # with a PP you need 3 NPs 

# To make sure that you always generate a grammatical sentence 
trees = [] 
while trees != []: 
    shuffle(words) 
    trees = parser.nbest_parse(words) 

for t in trees: 
    print t 
+0

고맙습니다. 파이썬 3을 사용하고있었습니다. 지원되는 nltk 버전이 없었습니다. 그러나 무한한 원숭이 정리로 안내해 주셔서 대단히 감사드립니다. . – RamyaV

+0

@RamyaV python 3을 지원하는 3.0alpha 버전을 다운로드 할 수 있습니다. http://nltk.org/nltk3-alpha/ – Xin