我知道我的问题听起来有点模糊,但我在网上找不到任何教程。我不是在寻求答案,而是寻求更多的解释。
BNF 的一个例子:
<prog> ::= “int main() { <stat_list> return 0; }”
<stat_list> ::= <stat>
| <stat_list> <stat>
<stat> ::= <cmpd_stat>
| <if_stat>
| <iter_stat>
| <assgn_stat>
| <decl_stat>
<cmpd_stat> ::= { <stat_list> }
<if_stat> ::= if ( <exp> ) <stat>
| if ( <exp> ) <cmpd_stat>
| if ( <exp> ) <stat> else <stat>
| if ( <exp> ) <cmpd_stat> else <stat>
| if ( <exp> ) <stat> else <cmpd_stat>
| if ( <exp> ) <cmpd_stat> else <cmpd_stat>
将其转换为 python 以使我的程序使用上述条件创建随机程序的最简单方法是什么?任何有用网站链接的帮助将不胜感激。
NLTK https://www.nltk.org/有一个包grammars https://www.nltk.org/api/nltk.html?highlight=grammar#module-nltk.grammar。通常用于句子分析,但没有什么可以阻止您使用它来创建遵循该规则的“程序”。
我认为 NLTK 只允许你定义上下文无关语法,所以我在这里给你留下一个我做的小例子:
from nltk import CFG
from nltk.parse.generate import generate
#Define your grammar from string
#You can define it using other methods, but I only know this xD
grammar = CFG.fromstring(""" S -> NP VP
VP -> V NP
V -> "mata" | "roba"
NP -> Det N | NP NP
Det -> "un" | "el" | "con" | "a" | "una"
N -> "bebé" | "ladrón" | "Obama" | "perrete" | "navastola" | "navaja" | "pistola" """)
''' This grammar creates sentences like:
El bebé roba a Obama
Baby steals Obama (in spanish)
'''
#With this we "create" all the possible combinations
grammar.productions()
#Here you can see all the productions (sentences) with 5 words
#created with this grammar
for production in generate(grammar, depth=5):
print(' '.join(production))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)