|
在python处理文本时,采用正则表达式替换,可以方便很多。主要用到 re 模块。
1、一个简单的文本替换例子:
import re
msg=file("test.htm","r+").read()
pattern = '<[^>]*?>'
rpl = ''
msg = re.sub(pattern,rpl,msg)
以上代码过滤掉一个html文件中的所有标记信息(<>中的内容),只保留文本信息
2、(?P<name>[0-9]{1}) 和\g<name>:
pattern = """<img src="\.\.\/images\/[a-b]{1}(?P<name>[0-9]{1})\.gif" width="\d+" height="\d+">"""
rpl = """image_\g<name>"""
msg = re.sub(pattern,rpl,msg)
在pattern中使用(?P<name>)匹配搜索内容,然后在rpl中采用 \g<name> 来代表原文中的内容,这样可以达到一些比较特殊的用途,比如重新安排显示格式等。如下例转换日期格式:
import re
msg = "03/24/2004" # convert to 2004-03-24
print msg
pattern = """(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<year>\d{2,4})"""
rpl = """\g<year>-\g<month>-\g<day>"""
msg = re.sub(pattern,rpl,msg)
print msg
参考资料:
【PDF】搜集整理:wwwit586com:一个pdf格式的详细介绍
正则表达式校验工具 - 我爱啦查询:可以马上看到正则表达式可以马上看到替换结果 |
|
|