我正在编写编码课程中为最终项目编写一些代码。我也是初学者。我在下面编写了一些代码来创建一首随机诗,但是每次运行它时,我总是会收到一个错误,指出某些单词不遵循语法规则
import nltk
nltk.download('words')
nltk.download('punkt')
from nltk.corpus import words
from nltk.tokenize import word_tokenize
from nltk.grammar import CFG
from random import choice
# Choose a random word from the English dictionary
chosen_word = choice(words.words())
# Define the context free grammar
grammar = CFG.fromstring("""
S -> NP VP
NP -> Det N
VP -> V NP
Det -> 'the' | 'a'
N -> 'cat' | 'dog' | 'bird' | 'tree' | 'flower' | 'chosen_word' | 'Fabrikoid'
V -> 'sings' | 'walks' | 'flies' | 'grows' | 'blooms'
""")
# Create a parser object
parser = nltk.ChartParser(grammar)
# Generate a random sentence using the chosen word
sentence = ""
while not sentence:
# Generate a parse tree for the chosen word
trees = list(parser.parse(word_tokenize(chosen_word)))
# Choose a random parse tree
tree = choice(trees)
# Generate a sentence from the parse tree
sentence = tree.label()
for subtree in tree.subtrees():
if subtree.label() in ["NP", "VP"]:
sentence += " " + " ".join(subtree.leaves())
# Print the generated poem
print("Here is your poem:")
print(sentence)
我运行了该程序,期待形成一种随机的诗歌。相反,我得到这个:
ValueError Traceback(最近一次调用最后一次)
在
2 帧 /usr/local/lib/python3.10/dist-packages/nltk/grammar.py 在 check_coverage(self, tokens) 663 如果丢失: 第664章 不服输 --> 665 引发值错误( 第666章 666【求月票】 % 丢失的 第667章)
ValueError:语法未涵盖某些输入单词:“'unimprovedness'”。
看起来您想将您选择的单词插入到语法中:
... 'flower' | 'chosen_word' | 'Fabrikoid' ...
。不过,您正在添加文字字符串 'chosen_word'
。
我建议使用 f 弦。在此处的开头字符串块之前放置
f
:CFG.fromstring(f"""
,然后使用 ... | '{chosen_word}' | ...