jO.*_*jO. 0 python regex utf-8
我的问题是,即使我使用utf-8,使用正则表达式和re.search()的Python也无法识别重音.这是我的代码串;
#! /usr/bin/python
-*- coding: utf-8 -*-
import re
htmlString = '</dd><dt> Fine, thank you. </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.', ' ', '</dt><dd>', 'Molt', 'b')
Run Code Online (Sandbox Code Playgroud)
所以问题是它不能识别é并因此停止.任何帮助,将不胜感激.我是一个Python初学者.
默认情况下,\w
只匹配ascii字符,它转换为[a-zA-Z0-9_]
.使用正则表达式匹配UTF-8字节已经够用了,更不用说只匹配字符了,你必须匹配字节范围.
您需要从UTF-8解码unicode
并使用该re.UNICODE
标志:
>>> re.search(SearchStr, htmlString.decode('utf8'), re.UNICODE).groups()
(u'</dd><dt>', u'Fine, thank you.', u' ', u'</dt><dd>', u'Molt', u'b\xe9')
Run Code Online (Sandbox Code Playgroud)
但是,您应该使用HTML解析器来处理HTML.例如,使用BeautifulSoup.它将正确处理您的编码和Unicode.
归档时间: |
|
查看次数: |
5896 次 |
最近记录: |