python (三)字符串处理

本文介绍了一种不使用正则表达式的文本预处理方法,详细步骤包括去除标点符号、转换大小写、替换数字等,适用于Python编程环境。
  1. 去除所有标点符号,需要去除的标点符号是如下几种: , . ! ? : ;

  2. 所有数字包括小数,整数,负数都替换成一个替代字符串: ==NUMBER==

  3. 所有大写字母全部转成小写

  4. 去除每行起始的所有空格

  5. 连续的空格缩短为单独的空格(除每行起始连续空格,见以上规则4

  6. 如果经过上述处理导致一行为空,则在此行处放置标记字符串:[REMOVED] 

在python (二)中,我用正则表达式处理的文本,如果不用正则表达式,要如何处理这段文本呢?

 

#!/usr/bin/env python
#coding:utf-8
import string
def noreto(stol):
    s = stol.lower().lstrip()
    s = s.replace(',','')
    s = s.replace('.','')
    s = s.replace('!','')
    s = s.replace('?','')
    s = s.replace(':','')
    s = s.replace(';','')
    s = replaceall('  ','',s)
    l = s.split(' ')
    if len(l) == 0:
        l.append(0,'[REMOVED]')
    finaly = ' '.join(l)
    #print finaly
    with open('test_output.txt','a') as fwuck:
        fwuck.write(finaly)
def replaceall(mul,sing,str):
    while str.find(mul) > -1:
        str = str.replace(mul,'')
    return str
with open('test_input.txt','r') as fruck:
    for line in fruck:
        noreto(line)

  还差一个替换数字为==NUMBER==

转载于:https://www.cnblogs.com/HugoLester/p/7247712.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值