你有字节数据。您需要 Unicode 数据。图书馆不应该为你解码吗?必须这样做,因为您没有 HTTP 标头,因此缺少编码。
编辑
虽然这听起来很奇怪,但 Python 似乎不支持其 Web 库中的内容解码。如果你运行这个程序:
#!/usr/bin/env python
import re
import urllib.request
import io
import sys
for s in ("stdin","stdout","stderr"):
setattr(sys, s, io.TextIOWrapper(getattr(sys, s).detach(), encoding="utf8"))
print("Seeking r\xe9sum\xe9s")
response = urllib.request.urlopen('http://nytimes.com/')
content = response.read()
match = re.search(".*r\xe9sum\xe9.*", content, re.I | re.U)
if match:
print("success: " + match.group(0))
else:
print("failure")
你会得到以下结果:
Seeking résumés
Traceback (most recent call last):
File "ur.py", line 16, in <module>
match = re.search(".*r\xe9sum\xe9.*", content, re.I | re.U)
File "/usr/local/lib/python3.2/re.py", line 158, in search
return _compile(pattern, flags).search(string)
TypeError: can't use a string pattern on a bytes-like object
这意味着.read() 正在返回原始字节而不是真正的字符串。也许你可以在doc for the urllib.request class 中看到一些我看不到的东西。我不敢相信他们真的希望你在.info() return 和<meta> 标签中扎根,自己找出愚蠢的编码,然后解码它,这样你就有了一个真正的字符串。那将是完全蹩脚的!我希望我是错的,但我花了很长时间寻找,在这里找不到任何有用的东西。
比较在 Perl 中做等价是多么容易:
#!/usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
binmode(STDOUT, "utf8");
print("Seeking r\xe9sum\xe9s\n");
my $agent = LWP::UserAgent->new();
my $response = $agent->get("http://nytimes.com/");
if ($response->is_success) {
my $content = $response->decoded_content;
if ($content =~ /.*r\xe9sum\xe9.*/i) {
print("search success: $&\n");
} else {
print("search failure\n");
}
} else {
print "request failed: ", $response->status_line, "\n";
}
当尽职尽责地运行时会产生:
Seeking résumés
search success: <li><a href="http://hiring.nytimes.monster.com/products/resumeproducts.aspx">Search Résumés</a></li>
您确定必须在 Python 中执行此操作吗?看看 Perl LWP::UserAgent 和 HTTP::Response 类比同等的 Python 类更丰富和更友好。看看我的意思。
加上 Perl,您可以获得更好的 Unicode 支持,例如完整的字形支持,这是 Python 当前所缺乏的。鉴于您试图去掉变音符号,这似乎是另一个加分项。
use Unicode::Normalize;
($unaccented = NFD($original)) =~ s/\pM//g;
只是一个想法。