python NLP数据集分割大文件

python NLP数据集分割大文件

NLP数据文件有时候特别大的文件,需要分割成N个小文件来处理

部分提取:可以提取N份,每份K行

全部分割:分割整个文件,每一份K行

python 复制代码
import os

def split_file(filename, outdir,num_lines):
    """ 将文件按行数进行分割 \n
        filename 文件名 \n
        num_lines 每份包含的行数 \n
    """
    file_name_without_path_and_extension = os.path.splitext(os.path.basename(filename))[0]

    with open(filename, 'r') as f:
        current_chunk = 1
        current_line = 0
        current_output = open(f"{outdir}{file_name_without_path_and_extension}{current_chunk}.txt", 'w')
        for line in f:
            current_output.write(line)
            current_line += 1
            if current_line >= num_lines:
                current_output.close()
                current_chunk += 1
                current_line = 0
                current_output = open(f"{outdir}{file_name_without_path_and_extension}{current_chunk}.txt", 'w')
        current_output.close()

def split_file_max_chunks(filename,outdir, num_lines, max_chunks):
    """ 将文件按行数进行分割 \n
        filename 文件名 \n
        num_lines 每份包含的行数 \n
        max_chunks 最大分出多少份 \n
    """
    file_name_without_path_and_extension = os.path.splitext(os.path.basename(filename))[0]

    with open(filename, 'r') as f:
        current_chunk = 1
        current_line = 0
        current_output = open(f"{outdir}{file_name_without_path_and_extension}{current_chunk}.txt", 'w')
        for line in f:
            current_output.write(line)
            current_line += 1
            if current_line >= num_lines:
                current_output.close()
                if current_chunk >= max_chunks:
                    break
                current_chunk += 1
                current_line = 0
                current_output = open(f"{outdir}{file_name_without_path_and_extension}{current_chunk}.txt", 'w')  # 这里更新了current_output
        current_output.close()

def main():
    large_filename = "./data/large_file_1G.txt"
    outdir="./docs/"
    num_lines = 1000  # 每份包含 1000 行
    split_file(large_filename,outdir, num_lines)
    
    # max_chunks = 30   # 最大分出 30 份
    # split_file_max_chunks(large_filename,outdir, num_lines, max_chunks)

   

if __name__ == "__main__":
    main()
相关推荐
集大周杰伦几秒前
基于 Python 的 ADS 自动化仿真框架与 API 使用指南
python·自动化·ads 自动化仿真·ads 程控·ads python
傻啦嘿哟3 分钟前
Python高效实现Excel与TXT文本文件数据转换指南
开发语言·python·excel
七宝大爷3 分钟前
第一个CUDA程序:从向量加法开始
android·java·开发语言
木心爱编程4 分钟前
Qt C++ 插件开发指南:插件架构设计与动态加载实战
开发语言·c++·qt
有什么东东4 分钟前
redis实现店铺类型查看
java·开发语言·redis
Henry Zhu1237 分钟前
23种设计模式介绍以及C语言实现
c语言·开发语言·设计模式
AAIshangyanxiu9 分钟前
基于R语言机器学习遥感数据处理与模型空间预测技术及实际项目案例分析
开发语言·机器学习·r语言·生态遥感·空间预测
我送炭你添花10 分钟前
我送炭你献花:Pelco KBD300A 模拟器项目总览
python·功能测试·pyqt·运维开发
LinHenrY122710 分钟前
初识C语言(数据在内存中的存储)
c语言·开发语言·算法