日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

用Python实现TXT文件分割

發(fā)布時間:2023/12/20 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用Python实现TXT文件分割 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

近些天想把一本很長的小說分割一下,拿來導入吾愛上很火的那個語音合成助手里,生成語音用來聽書;

先放打包好的文件:TXT分割.exe - 123云盤

正好我有ChatGPT的賬號,于是就去問了問這個AI,它給了個不錯的代碼,我又稍加改造,就有了下面的源碼:

import codecsinput_fn = input('請輸入分割文件名:\n(含后綴,不在同一目錄請輸入文件路徑,請勿添加引號):\n') output_fnh = input('請輸入分割后文件名前綴(勿加斜杠):\n') output_fls = int(input('請輸入分割后每文件行數(shù):\n'))def split_file(input_file, output_prefix, num_lines_per_file):# Open the input file in UTF-8 encodingwith codecs.open(input_file, 'r', encoding='utf-8') as f:# Create a counter for the current line numberline_number = 1# Create a counter for the current output file numberfile_number = 1# Create an output file with the correct file numberoutput_file = codecs.open(f'{output_prefix}_{file_number}.txt', 'w', encoding='utf-8')# Iterate over the lines in the input filefor line in f:# Write the line to the output fileoutput_file.write(line)# Increment the line counterline_number += 1# If the line counter is greater than the number of lines per file,# close the output file, increment the file counter, and create a new output fileif line_number > num_lines_per_file:output_file.close()file_number += 1line_number = 1output_file = codecs.open(f'{output_prefix}_{file_number}.txt', 'w', encoding='utf-8')# Close the last output fileoutput_file.close()# Test the function with an input file and a specified number of lines per output filesplit_file(input_fn,output_fnh,output_fls)

使用也非常簡單:

1.將py文件和txt文件放在同一個文件夾下(或者記下txt文件的路徑)。

2.然后用python解釋器運行py文件,輸入txt文件的名稱或路徑(包括后綴名),回車。

3.輸入分割后文件名前綴(這里不能加斜杠),回車。

4.輸入多少行每個文件,回車。

5.然后就能在py文件所在文件夾找到分割后的文件了。??

總結(jié)

以上是生活随笔為你收集整理的用Python实现TXT文件分割的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。