Python中list的语法nltk

2024-06-16 09:46:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须为python中的list创建一个语法nltk。我有一篇课文的语法:

grammar1 = nltk.CFG.fromstring("""
    S -> NP VP
    VP -> V NP | V NP PP
    PP -> P NP
    V -> "saw" | "ate" | "walked"
    NP -> "John" | "Mary" | "Bob" | Det N | Det N PP
    Det -> "a" | "an" | "the" | "my"
    N -> "man" | "dog" | "cat" | "telescope" | "kitchen"
    P -> "in" | "on" | "by" | "with"
    """)

sent = "the cat ate a telescope in the kitchen".split()
rd_parser = nltk.RecursiveDescentParser(grammar1)

for tree in rd_parser.parse(sent):
    print(tree)

现在,如何对list执行相同的操作?我需要用一个基本语法测试合法和非法list。我没有找到任何关于nltk和列表的信息,我真的不明白我该怎么做。。。在


Tags: theinnp语法listppcatsent
2条回答

注意,下面的代码行已经创建了一个(字符串)列表。在

sent = "the cat ate a telescope in the kitchen".split()

您还使用以下行为语法创建了递归下降解析器。请注意,您只需执行一次。在

^{pr2}$

现在,如果要测试不同的令牌列表,只需执行以下操作:

L = ["John", "walked", "the", "dog"]
result = rd_parser.parse(L)

您有一个可以应用于标记列表的解析器。你有一组不同格式的测试材料。引用你的comment:“空列表,带有一个标记的列表,带有多个标记的列表,带有数字、元组和词典的列表。”

解析器可以处理字符串的“序列”,在您的例子中,这意味着元素是字符串(每个字符串都是一个单词)的列表或元组。解析器不能处理其他任何事情;如果代码必须处理其他类型,请编写python代码,在解析器看到它们之前检查它们的类型。在

您将对内置函数^{}(首选)和^{}感兴趣。E、 g

if (isinstance(sent, (tuple, list)) and all(isinstance(w, str) for w in sent)):
    # A tuple or list of strings; try to parse it.
    trees = rd_parser.parse(sent)

相关问题 更多 >