[英]NLTK Generate sentences without two occurences of the same word in Python
我正在使用此NLTK代碼從demo_grammar生成句子(請參見下文),問題是諸如NN或NNNI之類的語法規則最終會導致諸如“創建創造”之類的句子。 我只對生成不會重復出現同一單詞的句子感興趣(即創建視頻軟件)。
我怎么能這樣做?
NLTK的generate.py
就是這樣: https : //github.com/nltk/nltk/blob/develop/nltk/parse/generate.py
我已經嘗試了generate.py
的演示代碼:
from nltk.grammar import CFG
from nltk.parse import generate
demo_grammar = """
S -> NP VP
NP -> Det N
PP -> P NP
VP -> 'slept' | 'saw' NP | 'walked' PP
Det -> 'the' | 'a'
N -> 'man' | 'park' | 'dog'
P -> 'in' | 'with'
"""
def demo(N=23):
print('Generating the first %d sentences for demo grammar:' % (N,))
print(demo_grammar)
grammar = CFG.fromstring(demo_grammar)
for n, sent in enumerate(generate(grammar, n=N), 1):
print('%3d. %s' % (n, ' '.join(sent)))
您可以按照Alexis的建議重寫語法,這意味着每個句子中特定位置的多個術語列表(名詞,動詞等)。
但是,您也可以應用后過濾策略(不必接觸語法):
這是您可以應用的過濾器:
from collections import Counter
f=lambda sent:False if Counter(sent.split(" ")).most_common(1)[0][1] > 1 else True
f("creation video software") # return True, good sentence
f("creation creation creation") # return False, bad sentence
f("creation software creation") # return False, bad sentence
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.