NLP第一阶段练习 简单词性标注

📅 2026/7/29 21:22:48
NLP第一阶段练习 简单词性标注
NLP第一阶段练习 简单词性标注代码# sequence_labeling.pyfromtypingimportList,Tupledefsimple_pos_tagging(text:str)-List[Tuple[str,str]]:简单的词性标注示例# 简化的词性标注规则实际应使用专业的NLP库如HanLP、LTP等nouns{电影,天气,手机,餐厅,比赛,游戏,演员,运动员,菜品,服务}verbs{看,去,是,有,做,吃,玩,说,听,看,买}adjectives{好看,不错,快,好,精彩,有趣,拖沓,卡顿,差}wordslist(text.replace(, ).replace(。,).split())result[]forwordinwords:ifwordinnouns:posn# 名词elifwordinverbs:posv# 动词elifwordinadjectives:posa# 形容词else:posx# 其他result.append((word,pos))returnresult# 使用更专业的库 - HanLPdefhanlp_ner_example():使用HanLP进行命名实体识别需要安装pip install hanlptry:importhanlp# 加载预训练模型hanlp.pretrained.mtl.CLOSE_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH NERhanlp.load(hanlp.pretrained.ner.MSRA_NER_BERT_BASE_ZH)text张三在北京的清华大学学习计算机科学。entitiesNER(text)print(命名实体识别结果:)print(f文本:{text})print(f实体:{entities})exceptImportError:print(请先安装HanLP: pip install hanlp)exceptExceptionase:print(fHanLP运行出错:{e})# 简单的命名实体识别规则示例defrule_based_ner(text:str)-List[Tuple[str,str,int,int]]:基于规则的简单命名实体识别entities[]# 人名规则简单示例person_patternr(张三|李四|王五|赵六)formatchinre.finditer(person_pattern,text):entities.append((match.group(),PERSON,match.start(),match.end()))# 地名规则location_patternr(北京|上海|广州|深圳)formatchinre.finditer(location_pattern,text):entities.append((match.group(),LOCATION,match.start(),match.end()))# 机构名规则org_patternr(清华大学|北京大学|复旦大学)formatchinre.finditer(org_pattern,text):entities.append((match.group(),ORG,match.start(),match.end()))returnentities# 示例使用if__name____main__:importre# 简单词性标注示例text我看好这部电影pos_resultsimple_pos_tagging(text)print(词性标注结果:,pos_result)# 命名实体识别示例sample_text张三从北京到上海的清华大学参加会议ner_resultrule_based_ner(sample_text)print(\n命名实体识别结果:,ner_result)# 尝试使用专业库# print(\n尝试使用HanLP进行专业NER:)# hanlp_ner_example()运行结果