深度问答之提取语料,导入了yml模块

根据目录下的yml文件循环创建同名文件夹,并从yml文件读取问答并给每个文件夹写入question和answer文件

 

#!/usr/bin/env python
# coding:utf8
# author:Z time:2018/9/12


"""
遍历循环,每个文件生成question和answer

"""

import yaml

import os

def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)

    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)

        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(path + ' 目录已存在')
        return False


yml_file_list=[]
path=os.path.dirname(os.path.abspath(__file__))
file_list=os.listdir(path)
for file in file_list:
    if file.endswith('yml'):
        yml_file_list.append(file)
        """
        循环创建文件夹
        """
        # # 定义要创建的目录
        # mkpath = "E:\\chatterbot-corpus-master\\chatterbot_corpus\\data\\chinese\\" + file[:-4]
        # # 调用函数
        # mkdir(mkpath)



for yml_file in yml_file_list:
    with open(yml_file, 'r', encoding="utf-8") as rf:
        ss = yaml.load(rf)
        aa=ss['conversations']

        index=1

        for i in aa:
            question=i[0]
            answer=i[1:]
            with open(yml_file[:-4]+'/question','a+',encoding='utf8')as f:

                f.write(question+'\n')
            with open(yml_file[:-4]+'/answer','a+',encoding='utf8')as f:
                for j in answer:

                    f.write(str(index)+j+'\n')
            index+=1

 

posted @ 2018-09-13 11:54  Operater  阅读(491)  评论(0编辑  收藏  举报