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()
相关推荐
Ulyanov16 分钟前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
码界筑梦坊19 分钟前
357-基于Java的大型商场应急预案管理系统
java·开发语言·毕业设计·知识分享
anzhxu23 分钟前
Go基础之环境搭建
开发语言·后端·golang
刀法如飞44 分钟前
一款Python语言Django框架DDD脚手架,助你快速搭建项目
python·ddd·脚手架
刀法如飞1 小时前
一款Python语言Django框架DDD脚手架,适合中大型项目
后端·python·领域驱动设计
yu85939581 小时前
基于MATLAB的随机振动仿真与分析完整实现
开发语言·matlab
赵钰老师1 小时前
【结构方程模型SEM】最新基于R语言结构方程模型分析
开发语言·数据分析·r语言
guygg881 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
gihigo19981 小时前
基于MATLAB实现NSGA-III的土地利用空间优化模型
开发语言·matlab
MediaTea1 小时前
Scikit-learn:数据集
人工智能·python·机器学习·scikit-learn