python把多个人声分离_如何在Python 3中将文件拆分为多个输出文件?

I have a problem statement:

splitfile(filename,numberoffiles)

A file of 13 lines, split in 3, would have output files of length 4, 4 and 5 if they cannot be evenly distributed. ( Can not have a difference greater than 1 line if they cant be evenly distributed)

I started learning python and I have to create a function that will split a file into smaller ones as specified in the parameters.

The thing I am having trouble with is I do not know how to approach this scenario due to it being based off of number of files and the concept of having a difference greater than 1 being non permissible.

解决方案

The essence of the question (as I understand it) is how to determine the number of lines that each output file will contain. This is what I came up with for Python 3.4.3:

def get_line_counts(total_lines, number_of_files):

base_size = total_lines // number_of_files

line_count_list = [base_size for i in range(number_of_files)]

files_with_an_extra_line = total_lines % number_of_files

for i in range(files_with_an_extra_line):

line_count_list[len(line_count_list) - (i + 1)] += 1

return line_count_list

for i, n in enumerate(get_line_counts(13, 3)):

print("file {0} will contain {1} line(s)".format(i, n))

resulting in

file 0 will contain 4 line(s)

file 1 will contain 4 line(s)

file 2 will contain 5 line(s)

The rest of the code would just be basic file I/O: read n lines from an input text file and write them to an output text file.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值