前年的斐波那契蹲在地上看着你,笑而不语

我之前那个更新hosts的脚本啊。

匹配的是开头的注释和结尾的注释。

然后那个站主没事总改注释。

结果我那个脚本动不动就失效。

然后我就得改正则重新提交。

改多了我就烦了。

就懒得更新hosts了。

今儿个我心情好。

打开脚本一看。

我他娘的为什么不直接匹配hosts内容?

为他娘的什么?

啊?

你敢睁大狗眼看看

119.161.83.27    google.com

吗?

一个IP,一个换行符。

啊?

啊?

要注释有个卵用?

啊?

r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} [^\n]+)\n'

啊??

 

 1 #encoding:utf-8
 2 import urllib
 3 import re
 4 import os
 5 
 6 url = 'http://www.360kb.com/kb/2_122.html'
 7 regexHosts = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} [^\n]+)\n'
 8 regexTimeUpdated = r'google hosts (\d\d\d\d\.\d\d?\.\d\d?)'
 9 
10 hostsPath = 'C:\\Windows\\System32\\drivers\\etc\\hosts'
11     
12 def retrievePage(url):
13     ''' 读取页面源代码。 '''
14     response = urllib.urlopen(url)
15     page = response.read()
16     return page
17 
18 def matchTimeUpdated(page):
19     ''' 从页面源码中匹配出hosts更新时间。 '''
20     timeUpdated = re.search(regexTimeUpdated, page)
21     if not timeUpdated:
22         return 'unknown time'
23     else:
24         return timeUpdated.group(1)
25 
26 def matchHostList(page):
27     ''' 从页面源码中匹配出host列表。 '''
28     result = re.findall(regexHosts, page, re.S)
29     
30     if not result:
31         return '#Hosts update failed.\n#May resolved by update the script.'
32     else:
33         return result
34 
35 def concatenateHosts(hosts):
36     ''' 把列表拼接成字符串。 '''
37     return '\n'.join(hosts)
38 
39 def addExtraInfo(srcString, extraInfo):
40     ''' 在第一行添加额外信息。'''
41     return extraInfo + '\n' + srcString
42 
43 def write2File(hosts, filePath):
44     ''' 写出到文件。 '''
45     f = open(filePath, 'w')
46     f.write(hosts)
47     f.close()
48     
49 def run():
50     ''' 主运行函数。 '''
51     page = retrievePage(url)
52     
53     hosts = matchHostList(page)
54     
55     extraInfo = '''#Hosts updated at %s
56 #Script written by mlxy@https://github.com/mlxy, feel free to modify and distribute it.
57 ''' %matchTimeUpdated(page)
58     hostsWithExtra = addExtraInfo(concatenateHosts(hosts), extraInfo)
59    
60     write2File(hostsWithExtra, hostsPath)
61     
62 if __name__ == '__main__':
63     run()
64     print 'Finished.'
啊???

啊?

posted @ 2015-04-11 12:21  Chihane  阅读(187)  评论(0编辑  收藏  举报