前几天有个需求,在百度上抓了一批serp的url,需求是对这些url进行提取每个url的域名、然后对域名计数去重,提取每个url的域名好弄,有现成的函数能用,就是这个计数去重,其实在自己的电脑上用shell命令一行就搞定,无奈在公司电脑上安装cygwin的时候总是出错,工作日也没有时间弄这个,所以干脆就找了个python的脚本。
比如说抓了十万个url,针对每个url提取出对应的域名,上代码:
from urlparse import urlparse
conn = MySQLdb.connect('localhost','root','','rank',charset='utf8') #连数据库,拿url
with conn:
cur = conn.cursor()
sql = 'select keyword,url,pcrank from t_rank_copy' #从表里拿数据
cur.execute(sql)
conn.commit()
rowNum = int(cur.rowcount)
for data in range(rowNum):
row = cur.fetchone()
with open('domain.txt',r'a+') as my:
#利用urlparse对解析每个url,提取域名
my.write(urlparse(row[1]).netloc+'\n')
print '写入完毕'把域名写到domain.txt以后,再进行计数去重:
#coding=utf-8
import operator
f = open("domain.txt")
count_dict = {}
for line in f.readlines():
line = line.strip()
count = count_dict.setdefault(line, 0)
count += 1
count_dict[line] = count
sorted_count_dict = sorted(count_dict.iteritems(), key=operator.itemgetter(1), reverse=True)
f1 = open('last.txt',r'a+')
for item in sorted_count_dict:
print "%s,%d" % (item[0], item[1])
f1.write(item[0]+'>'+str(item[1])+'\n')
f1.close()亲测好用,其实计数去重用shell一行就可以搞定:
cat domain.txt|sort|uniq -c|sort -r|head -100 > result.txt