关于unicode字符串的正则表达式

时间:2014-05-09 20:28:45

标签: python regex unicode

我正在尝试下载像这样的几百个韩语页面:

http://homeplusexpress.com/store/store_view.asp?cd_express=3

对于每个页面,我想使用正则表达式来提取"地址"字段,在上面的页面看起来像:

  

*주소:서울시광진구구의1동236-53

所以我这样做:

>>> import requests
>>> resp=requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')
>>> resp.encoding
'ISO-8859-1'
>>> # I wonder why it's ISO-8859-1, since I thought that is for Latin text (Latin-1).
>>> html = resp.text
>>> type(html)
<type 'unicode'>
>>> html
(outputs a long string that contains a lot of characters like \xc3\xb7\xaf\xbd\xba \xc0\xcd\xbd\xba\xc7\xc1\xb7\xb9\)
然后我写了一个脚本。我在.py文件上设置# -*- coding: utf-8 -*-并将其放在:

address = re.search('주소', html)

但是,re.search正在返回None。我在regex字符串上尝试使用和不使用u前缀。

通常我可以通过拨打.encode.decode来解决此类问题,但我尝试了一些事情而且卡住了。关于我缺少什么的任何指示?

2 个答案:

答案 0 :(得分:2)

根据html文档标题中的标记:

<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">

网页使用euc-kr编码。

我写了这段代码:

# -*- coding: euc-kr -*-

import re

import requests

resp=requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')
html = resp.text

address = re.search('주소', html)

print address

然后我使用euc-kr编码将其保存在gedit中。

我有一场比赛。

但实际上还有更好的解决方案!您可以为文件保留utf-8编码。

# -*- coding: utf-8 -*-

import re

import requests

resp=requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')

resp.encoding = 'euc-kr'
# we need to specify what the encoding is because the 
# requests library couldn't detect it correctly

html = resp.text
# now the html variable contains a utf-8 encoded unicode instance

print type(html)

# we use the re.search functions with unicode strings
address = re.search(u'주소', html)

print address

答案 1 :(得分:0)

来自请求documetation:当您发出请求时,请求会根据HTTP标头对响应的编码进行有根据的猜测

如果您检查了您的网站,我们可以看到服务器响应中没有编码:enter image description here

我认为在这种情况下唯一的选择是直接指定要使用的编码:

# -*- coding: utf-8 -*-

import requests
import re

r = requests.get('http://homeplusexpress.com/store/store_view.asp?cd_express=3')
r.encoding = 'euc-kr'
print re.search(ur'주소', r.text, re.UNICODE)
相关问题