NLP第一阶段练习 简单词性标注 代码 # sequence_labeling.py from typingimport List, Tupledef simple_pos_tagging ( text: str ) - > List[ Tuple[ str , str ] ] : """简单的词性标注示例""" # 简化的词性标注规则(实际应使用专业的NLP库如HanLP、LTP等) nouns= { '电影' , '天气' , '手机' , '餐厅' , '比赛' , '游戏' , '演员' , '运动员' , '菜品' , '服务' } verbs= { '看' , '去' , '是' , '有' , '做' , '吃' , '玩' , '说' , '听' , '看' , '买' } adjectives= { '好看' , '不错' , '快' , '好' , '精彩' , '有趣' , '拖沓' , '卡顿' , '差' } words= list ( text. replace( ',' , ' ' ) . replace( '。' , '' ) . split( ) ) result= [ ] for wordin words: if wordin nouns: pos= 'n' # 名词 elif wordin verbs: pos= 'v' # 动词 elif wordin adjectives: pos= 'a' # 形容词 else : pos= 'x' # 其他 result. append( ( word, pos) ) return result# 使用更专业的库 - HanLP def hanlp_ner_example ( ) : """使用HanLP进行命名实体识别(需要安装:pip install hanlp)""" try : import hanlp# 加载预训练模型 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} " ) except ImportError: print ( "请先安装HanLP: pip install hanlp" ) except Exceptionas e: print ( f"HanLP运行出错: { e} " ) # 简单的命名实体识别规则示例 def rule_based_ner ( text: str ) - > List[ Tuple[ str , str , int , int ] ] : """基于规则的简单命名实体识别""" entities= [ ] # 人名规则(简单示例) person_pattern= r'(张三|李四|王五|赵六)' for match in re. finditer( person_pattern, text) : entities. append( ( match . group( ) , 'PERSON' , match . start( ) , match . end( ) ) ) # 地名规则 location_pattern= r'(北京|上海|广州|深圳)' for match in re. finditer( location_pattern, text) : entities. append( ( match . group( ) , 'LOCATION' , match . start( ) , match . end( ) ) ) # 机构名规则 org_pattern= r'(清华大学|北京大学|复旦大学)' for match in re. finditer( org_pattern, text) : entities. append( ( match . group( ) , 'ORG' , match . start( ) , match . end( ) ) ) return entities# 示例使用 if __name__== "__main__" : import re# 简单词性标注示例 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() 运行结果