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()
相关推荐
l1t4 分钟前
将利用30行X算法求解数独的python程序转成DuckDB自定义函数并比较性能
数据库·python·算法·duckdb
墨雪不会编程9 分钟前
C++【string篇2】:从零基础开始到熟悉使用string类
java·开发语言·c++
光泽雨15 分钟前
ST语言与C#语言数据类型对比详解
开发语言·c#
vibag21 分钟前
Prompt提示词工程
python·语言模型·大模型·prompt
KevinGuo45722 分钟前
Selenium3自动化测试实战——基于python语言
开发语言·python·selenium
梦茹^_^29 分钟前
Flsk框架(自学)2
后端·python·flask·web框架
Tony Bai36 分钟前
Go 考古:Go 官方如何决定支持你的 CPU 和 OS?
开发语言·后端·golang
知无不研1 小时前
.练习- Java字符串之String类创建字符串之使用equals和==判断字符串是否相等
java·开发语言
NullPointer81 小时前
【剪映小助手源码精讲】第39章:CI流程
python·aigc
Slow菜鸟1 小时前
Java基础 | JWT登录场景化最优方案(一)
java·开发语言