Python Challenge 第 3 关攻略:re

Python Challenge3 关攻略:re


题目地址
http://www.pythonchallenge.com/pc/def/equality.html


题目内容

One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.

To see the solutions to the previous level, replace pc with pcc, i.e. go to: http://www.pythonchallenge.com/pcc/def/equality.html

Join us on IRC: irc.freenode.net #pythonchallenge


题目解法
- 网页标题是 re ,也就是正则表达式,说明要用到正则表达式这个模块。
- 图片是一个小蜡烛,左边三个大蜡烛,右边三个大蜡烛。
- 文字写着一个小字母,两边被刚好 3 个保镖环绕。

这是说要匹配到三个大写字母,一个小写字母,三个大写字母这样的组合,并且左右两边的大写字母不能多余三个。也就是说 &BBBaBBB7 是可以的,而 BBBBaBBB7 是不行的。一开始我在这里犯了错误,匹配出来很多无关信息。

查看网页源代码,发现 HTML 文档的注释中有一串乱码。我们就要用刚才提到的规则,从乱码中匹配出信息来。

下面先爬取网页源码,转换成文本格式,然后用正则表达式匹配三个大写字母包围一个小写字母,最后把匹配出来的小写字母拼接起来即可:

from urllib.request import urlopen
import re

url = 'http://www.pythonchallenge.com/pc/def/equality.html'

response = urlopen(url)
html = response.read()
text = str(html)
pattern = re.compile(r'<!--(.+)-->')
result = pattern.findall(text)
result = result[0]

letter = re.compile(r'[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]')
letters = letter.findall(result)
msg = ''.join(letters)
print(msg)

得到结果 linkedlist ,修改 URL ,放入浏览器然后回车:
http://www.pythonchallenge.com/pc/def/linkedlist.html

得到一个网页,显示 linkedlist.php
把网址改成:http://www.pythonchallenge.com/pc/def/linkedlist.php

进入下一关!

猜你喜欢

转载自blog.csdn.net/jpch89/article/details/81272056
今日推荐