我目前正在通过 python 挑战,我已经达到 4 级,看这里我只学习 python 几个月,我正在尝试学习 python 3 over 2.x 到目前为止这么好,除了当我使用这段代码时,这里是 python 2.x 版本:
import urllib, re
prefix = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
findnothing = re.compile(r"nothing is (\d+)").search
nothing = '12345'
while True:
text = urllib.urlopen(prefix + nothing).read()
print text
match = findnothing(text)
if match:
nothing = match.group(1)
print " going to", nothing
else:
break
因此,要将其转换为 3,我将更改为:
import urllib.request, urllib.parse, urllib.error, re
prefix = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
findnothing = re.compile(r"nothing is (\d+)").search
nothing = '12345'
while True:
text = urllib.request.urlopen(prefix + nothing).read()
print(text)
match = findnothing(text)
if match:
nothing = match.group(1)
print(" going to", nothing)
else:
break
因此,如果我运行 2.x 版本,它工作正常,通过循环,抓取 url 并走到最后,我得到以下输出:
and the next nothing is 72198
going to 72198
and the next nothing is 80992
going to 80992
and the next nothing is 8880
going to 8880 etc
如果我运行 3.x 版本,我会得到以下输出:
b'and the next nothing is 44827'
Traceback (most recent call last):
File "C:\Python32\lvl4.py", line 26, in <module>
match = findnothing(b"text")
TypeError: can't use a string pattern on a bytes-like object
因此,如果我在这一行中将 r 更改为 ab
findnothing = re.compile(b"nothing is (\d+)").search
我得到:
b'and the next nothing is 44827'
going to b'44827'
Traceback (most recent call last):
File "C:\Python32\lvl4.py", line 24, in <module>
text = urllib.request.urlopen(prefix + nothing).read()
TypeError: Can't convert 'bytes' object to str implicitly
有任何想法吗?
我对编程很陌生,所以请不要咬我的头。
_bk201