用Python实现TXT文件分割
生活随笔
收集整理的這篇文章主要介紹了
用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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用Stata命令(持续更新中)
- 下一篇: php 手机当扫描仪,只会用华为手机拍照