python - unicode 字符串的正则表达式

标签 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。我尝试了在正则表达式字符串上使用和不使用 u 前缀。

通常我可以通过调用 .encode.decode 来解决此类问题,但我尝试了一些方法,但遇到了困难。关于我所缺少的内容有什么指示吗?

最佳答案

根据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

关于python - unicode 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23573430/

相关文章:

python - PsychoPy:使用 XP 32 位通过 PC 的并行端口发送触发器

Python Singletons - 你如何在你的测试平台中摆脱(__del__)它们?

python - 如何转义 Bash 命令行参数中的空格

java - a^2nb^n 正则表达式接受 Java 中一个字符相对于其他字符的两次迭代?

python - 如何对文件中的每一行使用不同形式的正则表达式?

Python多处理,传递包含信号量的对象引用

regex - 查找两个可选标记之间的子字符串

java - 如何将具有Unicode编码的字符串转换为字母字符串

python - Unicode Django URL 参数

python-requests:获取响应内容的头部而不全部消耗