- #coding=utf-8
- # sitemap模板
- tpl = '<?xml version="1.0" encoding="utf-8"?>\n<urlset>\n<url>\n<loc>%s</loc>\n</url>\n</urlset>'
- tpl2 = '</loc>\n</url>\n<url>\n<loc>http:'
- tpl3 = '<?xml version="1.0" encoding="GB2312"?>\n<sitemapindex>\n%s</sitemapindex>'
- tpl4 = '<sitemap>\n<loc>%s</loc>\n</sitemap>\n'
- #基本参数配置
- k = 1 #计数器
- sitemap_name = 1 #sitemap编号
- sitemap_con = '' #sitemap内容
- sitemap_on = 0 #sitemap是否已生成,1生成,0未生成
- sitemap_ex = 'seoqx-' #sitemap前缀
- domain = 'http://www.test.com/' #域名
- sitemap_count = 40000 #每个sitemap包含url条数
- url_source = '1.txt' #全部url地址
- # sitemap生成函数
- def creat_sitemap(name, con, tpl):
- sitemap = open('%s%s.xml' % (sitemap_ex, name), 'w')
- con = tpl % con
- sitemap.write(con)
- sitemap.close()
- print '%s%s.xml' % (sitemap_ex, name)
- # 生成sitemap
- with open(url_source) as f:
- for line in f:
- sitemap_con += line
- k += 1
- if sitemap_on == 1:
- sitemap_on = 0
- if k > sitemap_count:
- sitemap_con = 'h' + sitemap_con.replace('h', '', 1).replace('\n', '',).replace('http:', tpl2)
- creat_sitemap(sitemap_name, sitemap_con, tpl)
- # 初始化
- k = 1
- sitemap_name += 1
- sitemap_con = ''
- sitemap_on = 1
- if sitemap_on == 0:
- sitemap_con = 'h' + sitemap_con.replace('h', '', 1).replace('\n', '',).replace('http:', tpl2)
- creat_sitemap(sitemap_name, sitemap_con, tpl)
- sitemap_con = ''
- # Sitemap索引
- for x in xrange(0,sitemap_name):
- url = domain + sitemap_ex + str(x + 1) + '.xml'
- sitemap_con += tpl4 % url
- creat_sitemap('sitemap', sitemap_con, tpl3)
复制代码
学习python是源于zero的《Python程序语言快速上手教程》,自己在传统机械行业维护企业站,网站数据不多,平均几百条数据。平时工作无外乎写写新闻发发外链,感到比较迷茫。
很认同zero的“有了需求再学习技术”。
ps:代码本地测试500w条数据用了53秒,本机2g内存,amd5200+ 老式台式机。大量数据用shell处理好像速度快,可惜对shell不是很懂。代码有错误欢迎拍砖,顺便求认证。
|