pythonchallenge2(众里寻她千百度)

今天遇到一个问题,大意是在一堆错综复杂的符号中找到极少的几个字母。可以点击这里http://www.pythonchallenge.com/pc/def/ocr.html,然后查看相应的网页源代码(page source),就可以查看完整的问题了。 
 

怎么用Python在一大堆复杂符号中寻找那几个字母呢?当然是要用Python强大的re模块(正则表达式)。不过用re之前还是要先读进page source。Python中的urllib模块提供了通过url读取网页的方法urllib.request.urlopen()。

下面是实例代码:

import os
import re
import urllib.request
def get_page_source(s):
    source=urllib.request.urlopen('http://www.pythonchallenge.com/pc/def/'+s).read();
    return source
#source_file=open('sourcefile.txt','wb')
pagesource=get_page_source('ocr.html')
#match=re.search(r'<--.*-->',pagesource.decode())
#text = re.compile(r'<!--((?:[^-]+|-[^-]|--[^>])*)-->', re.S).findall(pagesource.decode())[-1]
text = re.compile(r'<!--(.*)-->', re.S).findall(pagesource.decode())[0]
#fpg=match.group()
#source_file.write(fpg)
#source_file.close()
counts = {}
for c in text: counts[c] = counts.get(c, 0) + 1
counts
result=''.join(re.findall(r'[a-zA-Z]',text))
print(result)


你可能感兴趣的:(pythonchallenge2(众里寻她千百度))