命名实体有很多构建方式,这个代码是针对我所作的项目进行构建,方便我自己用,在使用中可以根据自己的方式进行修改,如有不懂可留言私信
import pandas as pd
cer_type = ['工程施工合同', '拍摄合作协议']
per_j = ['中节能财务有限公司', '天津市养颜堂生物技术有限公司']
per_y = ['古城中学', '丹赛县农业局']
contract_data = ['2019年12月19日', '2017年10月25日', '2018年4月18日', '2018年4月25日', '2012年7月15日', '2020年3月20日', '2021年12月31日']
cer_number = ['XF180822-0563', 'ISCT2018-0011', 'DS20180801', 'wy20211122']
money_big = ['贰拾壹万玖任伍佰贰拾元整', '伍万陆仟元整', '叁佰壹拾贰万壹仟叁佰零玖元', '叁万叁仟陆佰抑拾伍元整', '拾捌万柒仟叁佰贰拾圆整', '壹佰捌拾柒万叁仟贰佰', '壹拾伍万元整', '肆万伍仟元整',
'三万元整', '肆万贰仟玖佰元整']
money_small = ['219520.00元', '3121309.00元', '33685元', '187320.00元', '1873200.00元', '150000元', '45000元', '30000元',
'1,873,200.00元', '187,320.00元', '2369.440元']
train_df = pd.DataFrame({'txt': ['测试例子', '中节能财务有限公司在哪', '古城中学是乙方', '2017年10月25日能拥有吗贰拾壹万玖任伍佰贰拾元整我']})
# train_df = pd.read_csv('./data/train.txt', header=None, names=['txt'])
train_df['clear_txt'] = ''
train_df['lable_txt'] = ''
def cal_base(text, result_list, type_list, type_flag, type_flag_end):
per_j_str = []
per_j_end = []
for i in type_list:
if text.find(i) != -1:
# print(i)
# print(text.find(i), int(text.find(i) + len(i)))
per_j_str.append(text.find(i))
per_j_end.append(int(text.find(i) + len(i) - 1))
per_j_dict = {'per_j_str': per_j_str, 'per_j_end': per_j_end}
for i in range(len(per_j_str)):
for j in range(per_j_dict['per_j_str'][i], per_j_dict['per_j_end'][i] + 1):
result_list[j] = type_flag_end
result_list[per_j_dict['per_j_str'][i]] = type_flag
return result_list
for num, text in enumerate(train_df['txt']):
text = text.replace(' ', '').replace('\r', '')
ori_list = []
result_list = []
for i, j in enumerate(text):
ori_list.append(j)
result_list.append('O')
result_list = cal_base(text, result_list, cer_type, 'T-B', 'T-I')
result_list = cal_base(text, result_list, per_j, 'J-B', 'J-I')
result_list = cal_base(text, result_list, per_y, 'Y-B', 'Y-I')
result_list = cal_base(text, result_list, contract_data, 'D-B', 'D-I')
result_list = cal_base(text, result_list, cer_number, 'N-B', 'N-I')
result_list = cal_base(text, result_list, money_big, 'MB-B', 'MB-I')
result_list = cal_base(text, result_list, money_small, 'MS-B', 'MS-I')
print(text)
print(result_list)
tool_re = '\002'.join(ori_list)
train_df['clear_txt'][num] = tool_re
lable_re = '\002'.join(result_list)
train_df['lable_txt'][num] = lable_re
print(train_df)
train_df.to_csv('clear_tra_new.txt')
结果
测试例子
[‘O’, ‘O’, ‘O’, ‘O’]
中节能财务有限公司在哪
[‘J-B’, ‘J-I’, ‘J-I’, ‘J-I’, ‘J-I’, ‘J-I’, ‘J-I’, ‘J-I’, ‘J-I’, ‘O’, ‘O’]
古城中学是乙方
[‘Y-B’, ‘Y-I’, ‘Y-I’, ‘Y-I’, ‘O’, ‘O’, ‘O’]