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

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

代码

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

运行结果