python-小知识点 ---- 多字符串替换

一个长字符串或者一个文本文件做数据分析的时候经常遇到需要排除干扰项的需求,这时候就需要多字符串替换的功能

使用str的 replace函数

字符串常用的替换函数

比如说将标点替换成,使用replace连续替换多次即可

s = '''
	There was a card party at the rooms of Naroumoff, of the Horse Guards. 
	The long winter night passed away imperceptibly, and it was five o'clock in the morning before the company sat down
to supper. Those who had won ate with a good appetite; the others sat staring absently at their empty plates. When the 
champagne appeared, however, the conversation became more animated, and all took a part in it.
'''

b = s.replace(",", "").replace(".", "").replace(";", "")
print(b)
使用re 的sub函数替换

可以使用正则表达式来筛选你要替换的内容
如果你有指定的需要替换的字符串列表,且都是替换成同一个对象可以这样:

import re

s = '''
	There was a card party at the rooms of Naroumoff, of the Horse Guards. 
	The long winter night passed away imperceptibly, and it was five o'clock in the morning before the company sat down
to supper. Those who had won ate with a good appetite; the others sat staring absently at their empty plates. When the 
champagne appeared, however, the conversation became more animated, and all took a part in it.
'''
words = ["When", "There", "Those", "The"]

def replace_re():
	pattern = re.compile("|".join(words))
	print(pattern)
	r = re.sub(pattern, "", s)	# 全部替换成空
	print(r)

如果你需要指定字符替换成指定字符的话:

import re

s = '''
	There was a card party at the rooms of Naroumoff, of the Horse Guards. 
	The long winter night passed away imperceptibly, and it was five o'clock in the morning before the company sat down
to supper. Those who had won ate with a good appetite; the others sat staring absently at their empty plates. When the 
champagne appeared, however, the conversation became more animated, and all took a part in it.
'''
words = {"When": "when", "There": "there", "Those": "those", "The": "the"}

def replace_re():
	rep = dict((re.escape(k), v) for k, v in words.items())
	pattern = re.compile("|".join(rep.keys()))
	r = pattern.sub(lambda m: rep[re.escape(m.group(0))], s)
	print(r)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值