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()
相关推荐
Robot_Nav几秒前
基于深度强化学习的自主导航与避障策略研究
开发语言·深度强化学习·learning_based
故以往之不谏1 分钟前
JAVA--类和对象4.1--构造方法基础
java·开发语言·javascript
代码栈上的思考1 分钟前
消息队列自定义应用层协议设计:参数取舍与响应封装的核心逻辑
开发语言·php
青瓷程序设计2 分钟前
【基于 YOLO的咖啡豆果实成熟度检测系统】+ Python+算法模型+目标检测+2026原创
python·算法·yolo
天才测试猿3 分钟前
Python接口自动化测试之Token详解及应用
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
cch89184 分钟前
PHP与C语言:从网页到内核的编程对决
c语言·开发语言·php
lly2024065 分钟前
PHP 字符串处理详解
开发语言
csbysj20209 分钟前
HTML 头部
开发语言
童园管理札记11 分钟前
2026实测|GPT-4.5+Agent智能体:3小时搭建企业级客服系统,附完整源码与部署教程(二)
人工智能·python
踏雪羽翼17 分钟前
android 使用Gemini大模型实现图片处理
android·开发语言·ai聊天·ai抠图·ai生图·gemini大模型