根据标签提取词的代码例如从trainconll文件中读取以下数据湖 B-prov北 I-prov省 E-prov松 B-district滋 I-district市 E-district八 B-town宝 I-town镇 E-town丝 B-community线 I-community潮 I-community村 E-community五 B-village_group组 E-village_gro
打开文件
with open("train.conll", "r", encoding="utf-8") as f: # 读取文件内容 content = f.read() # 按行分割 lines = content.split("\n") # 初始化变量 words = [] # 遍历每一行 for line in lines: # 如果行为空,则跳过 if not line: continue # 按空格分割 parts = line.split(" ") # 取出标签 label = parts[1] # 如果标签是省、市、区、县、镇、村、街道、社区、小区、村庄、组、路、街、巷、弄、号、楼、单元、室、部门、公司、学校、医院、银行、酒店、餐厅、商场、公园、电影院、机场、火车站、地铁站、公交站、港口、码头、桥、隧道、广场、大厦、楼盘、景点、名胜古迹等,则将该词加入words列表 if label in ["B-prov", "I-prov", "E-prov", "B-city", "I-city", "E-city", "B-district", "I-district", "E-district", "B-town", "I-town", "E-town", "B-community", "I-community", "E-community", "B-village_group", "E-village_group", "B-road", "I-road", "E-road", "B-subpoi", "I-subpoi", "E-subpoi"]: # 取出词 word = parts[0] # 将词加入words列表 words.append(word) # 将words列表中的词用换行符分隔并输出到ci.txt文件中 with open("ci.txt", "w", encoding="utf-8") as output: output.write("\n".join(words)
AI 优化版
原文地址:http://www.cveoy.top/t/topic/hwyO 著作权归作者所有。请勿转载和采集!