在NLTK中从解析树文件学习PCFG的问题求助
从解析树学习PCFG:解决生成式无法替换为自定义treeData的问题
最近我也卡在过类似的问题上——从解析树文件学习PCFG时,生成式总是默认用内置函数类型,没法替换成自己的treeData内容。结合你提供的示例解析树,给你几个可行的解决思路:
1. 先把解析树字符串转成可操作的结构
首先得确保你手里的解析树字符串能被正确解析,你给的示例最后少了一个闭合括号,先补全再处理。比如用NLTK的话,这么转:
from nltk import Tree # 补全闭合括号的解析树字符串 tree_str = "(S (DECL_MD (NP_PPSS (PRON_PPSS (i i))) (VERB_MD (pt_verb_md need)) (NP_NN (ADJ_AT (a a)) (NOUN_NN (flight flight)) (PREP_IN (pt_prep_in from))) (AVPNP_NP (NOUN_NP (charlotte charlotte))))" tree = Tree.fromstring(tree_str)
只有转成结构化的树,才能后续提取自定义的产生式规则。
2. 手动遍历解析树,生成自己的treeData产生式
很多NLP库的PCFG学习工具默认用内置的Production类,如果你想替换成自己的treeData,不如手动遍历树来统计规则:
- 递归遍历每个非终结符节点
- 记录每个父节点到子节点的展开规则
- 用字典统计每条规则的出现次数,完全自定义规则格式
示例代码如下:
# 用来存储自定义产生式的统计结果 production_stats = {} def extract_productions(tree_node): # 跳过叶子节点(终结符) if not isinstance(tree_node, Tree): return # 获取当前节点的非终结符标签 parent_label = tree_node.label() # 处理子节点:子树取标签,叶子取字符串 child_labels = [] for child in tree_node: if isinstance(child, Tree): child_labels.append(child.label()) else: child_labels.append(child) # 把产生式存成元组作为字典键 production_key = (parent_label, tuple(child_labels)) # 统计次数 production_stats[production_key] = production_stats.get(production_key, 0) + 1 # 递归处理所有子节点 for child in tree_node: extract_productions(child) # 提取你需要的treeData产生式 extract_productions(tree)
这里的production_stats就是完全基于你的解析树生成的自定义产生式,和内置函数无关。
3. 若要兼容库的PCFG,转换自定义规则格式
如果你必须用库的PCFG结构,那就把自定义的treeData规则转换成库要求的格式。比如NLTK的Production需要用Nonterminal和Terminal对象构建,示例如下:
from nltk.grammar import Nonterminal, Terminal, Production custom_productions = [] for (parent, children), count in production_stats.items(): # 把父标签转成Nonterminal对象 parent_nt = Nonterminal(parent) child_symbols = [] for child in children: # 假设小写字符串是终结符,大写/带后缀的是非终结符 if isinstance(child, str) and child.islower(): child_symbols.append(Terminal(child)) else: child_symbols.append(Nonterminal(child)) # 构建符合库要求的Production对象 prod = Production(parent_nt, child_symbols) custom_productions.append((prod, count))
这样就能把你的treeData规则无缝接入库的PCFG学习流程里,不会再被内置函数干扰。
内容的提问来源于stack exchange,提问作者Ray92
相关产品推荐
相关产品推荐

