kgrag/app_pkg/contentprocess/contentprocess.py
2026-06-30 13:35:52 +08:00

49 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from phrasetree.tree import Tree
import hanlp
def extract_unique_nouns_from_file(content, model):
"""
从指定的文本文件中提取所有唯一的名词NN去除 '**' 并去重,保持首次出现顺序。
参数:
file_path (str): 输入文本文件的路径。
model: HanLP 预训练模型实例(可选)。如果未提供,则自动加载默认模型。
返回:
list: 提取到的唯一名词字符串列表,如 ['转向节', '螺栓', ...]
"""
# 1. 使用 HanLP 进行句法分析获取成分句法树con
doc = model(content)
# 2. 定义递归函数提取所有叶子节点为字符串的 NN 节点
def extract_nn(tree):
res = []
if isinstance(tree, Tree):
if tree.label() == 'NN' and len(tree) == 1 and isinstance(tree[0], str):
res.append(['NN', [tree[0]]])
else:
for child in tree:
res.extend(extract_nn(child))
return res
# 3. 提取所有 NN 节点
nn_list = extract_nn(doc['con'])
# print(f'共提取到 NN 节点:{len(nn_list)}')
# 4. 过滤掉词为 '**' 的项
filtered = [rec for rec in nn_list if rec[1][0] != '**']
# 5. 去重,保持顺序
seen = set()
unique_nn = []
for rec in filtered:
key = (rec[0], rec[1][0]) # 使用 (标签, 词语) 作为唯一键
if key not in seen:
seen.add(key)
unique_nn.append(rec[1][0])
print(f'共提取到 (去重并过滤后)关键词:{len(unique_nn)}')
print(f'输出提取到的关键词:{unique_nn}')
return unique_nn