python循环写入txt文件,防止内容被覆盖

import numpy as np

if __name__ == '__main__':
    guid = 0
    tokens = np.array(['CLS', 'i', 'want', 'to', 'fly', 'from', 'baltimore', 'to', 'dallas', 'round', 'trip', 'SEP'])
    input_ids = [101, 1045, 2215, 2000, 4875, 2013, 6222, 2000, 5759, 2461, 4440, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    attention_mask = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    token_type_ids = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    intent_label = 12
    slot_labels_ids = [-100, 2, 2, 2, 2, 2, 73, 2, 114, 98, 99, -100, -100, -100, -100, -100, -100, -100, -100, -100,
                       -100,
                       -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
                       -100,
                       -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100]

    a = str(guid)
    b = [str(x) for x in tokens]
    c = [str(x) for x in input_ids]
    d = [str(x) for x in attention_mask]
    e = [str(x) for x in token_type_ids]
    g = str(intent_label)
    h = [str(x) for x in slot_labels_ids]
    # 写入文件时不能直接写入list,此时利用join()函数写入
    with open('atis_train.txt', 'a', encoding='utf-8') as f:
        f.write('guid:' + a + '\n')
        f.write('tokens:')
        f.write(''.join([str(x) + ' ' for x in tokens]) + '\n')
        f.write('input_ids:')
        f.write(''.join([str(x) + ' ' for x in input_ids]) + '\n')
        f.write('attention_mask:')
        f.write(''.join([str(x) + ' ' for x in attention_mask]) + '\n')
        f.write('token_type_ids:')
        f.write(''.join([str(x) + ' ' for x in token_type_ids]) + '\n')
        f.write('intent_label:')
        f.write(''+ g + '\n')
        f.write('slot_labels:')
        f.write(''.join([str(x) + ' ' for x in slot_labels_ids]) + '\n')
    f.close()
发布了41 篇原创文章 · 获赞 44 · 访问量 7668

猜你喜欢

转载自blog.csdn.net/tailonh/article/details/104988100