python文本编辑: re.sub-------读取文本,去除指定字符并保存

现在有这样一个任务:
我们有一个文本,内容如下:

ws0012cs3d4 这,里。3是.一!?些a文 Z本...

文本里面有中英文标点符号,英文字符,数字,字母,中文,空格等等,现在我们需要把这些文本按行读取,前面的标号(ws0012cs3d4 )保持不变,后面文本过滤成仅包含中文文本的数据,然后把标号和文本重新拼起来,如下形式:

ws0012cs3d4 这里是一些文本

  

保存在新的文件中。

代码如下:

# -*- coding: utf-8 -*-
 '''
 get txt file ,
 remove all numbers , symbles, tab ,prosody in each txt and save it in a new txt ;
 save txt in a new file which an be use in mtts 
 这里有两个函数,分别实现了不同功能,可以随意使用
 '''
 
 from __future__ import unicode_literals
 import re
 import os
 
 '''
 删除文本中的奇数行
 '''
 def remove_lines(txtfile):
 with open(txtfile) as reader, open('newfile.txt', 'w') as writer:
     for index, line in enumerate(reader):
         if index % 2 == 0:
             writer.write(line)
 return 'newfile.txt'

 
 def _txt_preprocess(txtfile):
     with open(txtfile) as reader, open('newfile2.txt', 'w') as writer:
         txtlines = [x.strip() for x in reader.readlines()]
         for line in txtlines:
             num, txt = line.split(' ', 1)    # 把取出的一行按空格切分且只切分一次
             txt = re.sub('[,.,。、:;?!… “ ”# 0-9 a-z A-Z a-zA-Z]', '', txt)    # []内是希望过滤掉的所有符号,最后两个是大小写全角英文字符
             space = ' '
             changeline = '
'
             tmp = num + space + txt + changeline    #重新拼接文本
             writer.write(tmp)
 
 
 
 
 if __name__ == '__main__':
     import argparse
     parser = argparse.ArgumentParser(
         description="convert mandarin_txt and wav to label for merlin.")
     parser.add_argument(
         "txtfile",
         help=
         "Full path to txtfile which each line contain num and txt (seperated by a white space) "
     )
     args = parser.parse_args()
 
     _txt_preprocess(args.txtfile)

  

原文地址:https://www.cnblogs.com/gstblog/p/11649165.html