Python中的正则表达式匹配中文问题
来源:互联网 发布:大数据行业前景 编辑:程序博客网 时间:2024/04/28 18:29
python中正则表达式匹配中文是没有问题的,但是其中有一个关键点,那就是pattern中的中文编码必须和要匹配字符串保持一致;下面使用一个例子来说明:
# -*- coding: utf-8 -*-
'''
test.html内容为 :
<div id='author_' >作 者: (美)埃克尔 著,陈昊鹏 译</div>
<div id='publisher_'>出 版 社: 机械工业出版社</div>
<ul >
<li>出版时间: 2007-6-1</li>
<li>字 数: </li>
<li>版 次: 1</li>
<li>页 数: 880</li>
<li>印刷时间: 2007-6-1</li>
<li>开 本: </li>
<li>印 次: </li>
<li>纸 张: 胶版纸</li>
<li>I S B N : 9787111213826</li>
<li>包 装: 平装</li>
</ul>
'''
import re
import chardet #用于检测str的编码
#读文件
def readContent():
f = file(r'/home/fzhong/test.html','r')
content = f.read()
f.close()
return content
#检测str的编码
def checkEncoding(str):
return chardet.detect(str)['encoding']
def extractAttrValue(regx):
p = re.compile(regx)
attrValue = p.search(self.dataStr).group(1).strip()
return attrValue
if __name__ == '__main__':
content = readContent()
#因为这里的test.html为gb2312编码,所以这里encoding应该为gb2312
encoding = checkEncoding(content)
p_isbn = u'<li>I S B N :(.*?)</li>'.encode(encoding )
isbn = extractAttrValue(p_isbn)
#pattern为unicode,转为和content一样的编码,然后执行匹配
p_pub_date = u'<li>出版时间:(.*)</li>'.encode(encoding )
pubDate = extractAttrValue(p_pub_date)
p_edition_num = u'<li>版 次:(.*?)</li>'.encode(encoding )
editionNum = extractAttrValue(p_edition_num)
p_page_num = u'<li>页 数:(.*?)</li>'.encode(encoding )
pageNum = extractAttrValue(p_page_num)
p_author = ur'作 者:(.*?)</div>'.encode(encoding )
author = extractAttrValue(p_author)
p_publisher = ur'出 版 社:(.*?)</div>'.encode(encoding )
publisher = extractAttrValue(p_publisher)
这里有几个关键点:
p_pub_date = u'<li>出版时间:(.*)</li>'.encode(encoding )
执行一个unicode到encoding编码的转换;
当然在上面的脚本中也可以这样:
p_pub_date = '<li>出版时间:(.*)</li>'.decode('UTF-8').encode(encoding )
- Python中的正则表达式匹配中文问题
- Python正则表达式处理中文中的匹配
- python正则表达式匹配中文
- python正则表达式匹配中文
- Python正则表达式匹配中文
- Python正则表达式匹配中文
- python 正则表达式匹配中文
- python正则表达式中文匹配
- Python正则表达式匹配中文
- Python中正则表达式对中文的匹配问题
- Python中正则表达式对中文的匹配问题
- Python中正则表达式对中文的匹配问题
- 正则中的中文匹配问题
- Python如何使用正则表达式匹配中文
- python中的正则表达式(模式匹配)
- 正则表达式匹配中文
- 正则表达式 匹配中文
- 正则表达式匹配中文
- LINQ 快速开发设计最佳实践
- Web 设计与开发终极资源
- 很强悍的js获取request参数的方法
- Sun 推荐的命名规范
- C#中的数据类型
- Python中的正则表达式匹配中文问题
- 毕业
- 可证明安全随笔
- tomcat5.5 整合 iis6.0
- Clone a MDD Lib,快速修改MDD层lib
- lock vs Monitor vs Mutex之间的区别
- POST上传
- .Net比较奇怪的问题
- centos 安装 openoffice 3