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

yipeiwu_com6年前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设计】。

相关文章

Tensorflow 合并通道及加载子模型的方法

Tensorflow 合并通道及加载子模型的方法

最近在使用Tensorflow 实现DNN网络时,遇到一些问题。目前网上关于Tensorflow的资料还比较少,现把问题和解决方法写出来,仅供参考。 (1)将两个子模型的输出合并到一个通...

python调用百度语音REST API

本文实例为大家分享了python调用百度语音REST API的具体代码,供大家参考,具体内容如下 (百度的rest接口的部分网址发生了一定的变化,相关代码已更新) 百度通过 REST...

Python中动态检测编码chardet的使用教程

前言 在互联网的世界里,每个页面都使用了编码,但是形形色色的编码让我们的代码何以得知其棉麻格式呢?charset将很好的解决这个问题。 1. chardet chardet是Pytho...

python面试题之列表声明实例分析

python面试题之列表声明实例分析

本文实例讲述了python面试题之列表声明。分享给大家供大家参考,具体如下: 下面程序输出的结果为? val = [['a']*2]*2 print val val[0][1]='b...

Python实现感知器模型、两层神经网络

Python实现感知器模型、两层神经网络

本文实例为大家分享了Python实现感知器模型、两层神经网络,供大家参考,具体内容如下 python 3.4 因为使用了 numpy 这里我们首先实现一个感知器模型来实现下面的对应关系...