python分割一个文本为多个文本的方法

yipeiwu_com5年前Python基础

本文实例为大家分享了python分割一个文本为多个文本,供大家参考,具体内容如下

# load file
# for each row
## if match
## output
 
def main():
 file_source = './reading_questions.txt'
 #target_dir = ''
 file_in = open(file_source,'r')
 template_str = 'TARGET'
 
 outfilename = './head.txt'
 output_content = ''
 while 1:
 line = file_in.readline()
 if not line:
 break
 
 if line.find(template_str) != -1:
 write_file(outfilename,output_content)
 outfilename = './'+line+'.txt' # output file tile
 output_content = ''
 else:
 output_content += line # append 
 write_file(outfilename,output_content) #for the last file
 # close file stream
 file_in.close()
 
def write_file(filename, filecontent):
 file_out = open(filename,'w') # create file
 file_out.write(filename) 
 file_out.write(filecontent)
 file_out.close()
 
main()

cygwin+python3下报错:UnicodeDecodeError: 'gb2312' codec can't decode byte 0xac in position 25: illegal multibyte sequence

修改打开文件参数

file_in = open(file_source,'r',encoding='UTF-8')

修改为如下

# load file
# for each row
## if match
## output
 
def main():
 print ('hhh')
 file_source = 'listening_questions.txt'
 #target_dir = ''
 file_in = open(file_source,'r',encoding='UTF-8')
 template_str = 'ZTPO'
 
 outfilename = 'head' #first file before match target 
 output_content = ''
 while 1:
 line = file_in.readline()
 if not line:
 break
 
 if line.find(template_str) != -1:
 write_file(outfilename,output_content)
 outfilename = line.strip('\n')
 output_content = '' # clear content of output file
 else:
 output_content += line # append content 
 write_file(outfilename,output_content) #for the last file
 # close file stream
 file_in.close()
 
def write_file(filename, filecontent):
 outfilename = './'+filename+'.txt' # output file tile
 file_out = open(outfilename,'w',encoding='UTF-8') # create file
 file_out.write(filename) 
 file_out.write(filecontent)
 file_out.close()
 
main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python pycharm最新版本激活码(永久有效)附python安装教程

PyCharm 是一款功能强大的 Python 编辑器,具有跨平台性,鉴于目前最新版 PyCharm 使用教程较少,为了节约时间,来介绍下python pycharm最新版本激活码,本文...

Python实现的选择排序算法原理与用法实例分析

Python实现的选择排序算法原理与用法实例分析

本文实例讲述了Python实现的选择排序算法。分享给大家供大家参考,具体如下: 选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中...

如何解决django-celery启动后迅速关闭

日志中也没有打印什么明显的错误,只是显示连接了rabbitmq后就关闭了 [2019-09-11 06:08:45,729: INFO/Beat] beat: Starting......

python验证码图片处理(二值化)

python验证码图片处理(二值化)

写在最前面: 这个我打算分几次写,由于我们通过selenium拿到的图片会很模糊,所以使用Tesseract识别之前要对图片先进行处理。 第一步就是二值化,设定阈值,低于阈值全部为白色(...

python实现关键词提取的示例讲解

新人小菜鸟又来写博客啦!!!没人表示不开心~~(>_<)~~ 今天我来弄一个简单的关键词提取的代码 文章内容关键词的提取分为三大步: (1) 分词 (2) 去停用词 (...