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

63 lines
2.9 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
import requests
content = """
汽车底盘主要包括以下几个部分:
1. **车架**:作为汽车的基础骨架,支撑着发动机、车身和其它部件。
2. **悬架系统**:包括弹簧和减震器等,用于缓冲路面不平带来的震动。
3. **转向系统**:使汽车能够按照驾驶员的意愿改变行驶方向。
4. **制动系统**:用于减速或停车,包括制动踏板、制动总泵、制动片等。
5. **传动系统**:将发动机的动力传递给车轮,包括离合器、变速器、驱动轴等。
例如陕汽德龙X5000 重卡的底盘采用了高强度轻量化设计的车架及悬架系统,通过低碳合金钢和 CAE 模拟优化设计,等宽直大梁车架结构和少片变截面钢板弹簧结构设计,屈服强度提高近 $50\%$,承载力、稳定性、平顺性远优于国内同级车型。底盘应用大量轻量化材料及工艺,整车轻量化水平行业领先。
相关图示:![汽车底盘](http://192.168.0.46:9988/output/images/950efc3ec46e98cf719e76c672bc7a59ba23ea5184276b2cad1a28f763e8b3ce.jpg)
"""
print("正在加载 HanLP 模型...")
HanLPmodel = hanlp.load(hanlp.pretrained.mtl.CLOSE_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH)
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'共提取到 NN 节点(去重并过滤 ** 后):{len(unique_nn)}')
return unique_nn
fenci_word = extract_unique_nouns_from_file(content,model=HanLPmodel)
print(fenci_word)