Python + Regex + UTF-8无法识别重音符号

时间:2013-03-06 11:10:09

标签: python regex utf-8

我的问题是,即使我使用utf-8,使用正则表达式和re.search()的Python也无法识别重音。这是我的代码串;

#! /usr/bin/python
-*- coding: utf-8 -*-
import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies.'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ (\w+) (\w+)'

Result = re.search(SearchStr, htmlString)

if Result:
print Result.groups()

passavol23:jO$ catalanword.py
('</dd><dt>', 'Fine, thank you.', '&#160;', '</dt><dd>', 'Molt', 'b')

所以问题是它不能识别é因此停止。任何帮助,将不胜感激。我是Python的初学者。

1 个答案:

答案 0 :(得分:7)

默认情况下,\w仅匹配ascii字符,它会转换为[a-zA-Z0-9_]。使用正则表达式匹配UTF-8字节已经足够困难了,更不用说只匹配字符了,你必须匹配字节范围。

您需要从UTF-8解码为unicode并改为使用re.UNICODE flag

>>> re.search(SearchStr, htmlString.decode('utf8'), re.UNICODE).groups()
(u'</dd><dt>', u'Fine, thank you.', u'&#160;', u'</dt><dd>', u'Molt', u'b\xe9')

但是,您应该使用HTML解析器来处理HTML。例如,使用BeautifulSoup。它将为您正确处理编码和Unicode。

相关问题