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()
相关推荐
amy_jork3 分钟前
npm删除包
开发语言·javascript·ecmascript
浪成电火花1 小时前
(deepseek!)deepspeed中C++关联部分
开发语言·c++
茉莉玫瑰花茶1 小时前
Qt 常用控件 - 9
开发语言·qt
独行soc1 小时前
2025年渗透测试面试题总结-18(题目+回答)
android·python·科技·面试·职场和发展·渗透测试
S01d13r2 小时前
gunicorn + flask 处理高并发请求
python·flask·gunicorn
艾伦~耶格尔2 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
杜子不疼.2 小时前
《Python列表和元组:从入门到花式操作指南》
开发语言·python
pan0c232 小时前
数据处理与统计分析 —— numpy入门
python·numpy
max5006002 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
WYH2872 小时前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#