python创建txt文件_Python文件读写:字典dict与txt文件互相转换


label_to_id:

B-LOC 0
B-ORG 1
B-PER 2
I-LOC 3
I-ORG 4
I-PER 5
O 6

dict->txt

    with open('data/label_dict.txt', 'w') as dict_f:
        for k, v in label_to_id.items():
            dict_f.write(str(k) + ' ' + str(v) + '\n')

txt->dict

    label_dict={}
    with open('data/label_dict.txt', 'r') as dict_f:
        for line in dict_f.readlines():
            line=line.strip()
            k,v=line.split(' ')
            label_dict[k]=int(v)
posted @ 2022-02-22 22:57  zae  阅读(496)  评论(0编辑  收藏  举报