我目前正在经历python挑战,并且我已经达到了4级,see here才学习python几个月了,到目前为止,我正在尝试通过2.x来学习python 3,除了当我使用这段代码时,这是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
match = findnothing(b"text")
TypeError: can't use a string pattern on a bytes-like object
所以如果我在这一行中将r更改为b
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
text = urllib.request.urlopen(prefix + nothing).read()
TypeError: Can't convert 'bytes' object to str implicitly
有任何想法吗?
我是编程的新手,所以请不要犹豫.
_bk201