初次在ubuntu下使用python进行简单的统计

昨天花了半天了解了python语言,今天写个程序试一下效果

#-*- coding:utf-8 -*-
#统计CDN数量和比例
import glob
import string
infile = glob.glob('*.sites')
outfile = file('1.result','w')
length = len(infile)
for i in infile:
temp = file(i)
cnt = 0
while True:
line = temp.readline()
if len(line) == 0:
break
cnt=cnt+1
outfile.write(string.ljust(i[:-6],15))
outfile.write(string.ljust(str(cnt),15))
outfile.write(string.ljust(str(cnt)+'%',15)+'\n')
temp.close()
outfile.close()

#统计各网站使用的CDN数量,详细列表和排序
class Record:
website = ''
number = 0
cdn = []
def __init__(self,website,number,cdn):
self.website = website
self.number = number
self.cdn = cdn

infile2 = file('cntop100')
outfile = file('2.result','w')
li = []
while True:
line = infile2.readline()
if len(line) == 0:
break
tempnumber = 0
tempcdn = []
for i in infile:
tempfile = open(i)
while True:
templine = tempfile.readline()
#print templine
if len(templine) == 0:
break
if cmp(templine,line) == 0:
tempnumber = tempnumber+1
tempcdn.append(i[:-6])
tempfile.close()
record = Record(line,tempnumber,tempcdn)
li.append(record)

li.sort(lambda x,y: cmp(x.number, y.number),reverse=True)
for l in li:
outfile.write(string.ljust(l.website[:-1],30))
outfile.write(string.ljust(str(l.number),15))
if l.number != 0:
for c in l.cdn:
outfile.write(c)
if c != l.cdn[-1]:
outfile.write(',')
outfile.write('\n')
else:
outfile.write('--\n')

infile2.close()
outfile.close()


#-*- coding:utf-8 -*-
这是用来解决中文乱码问题的

glob是一个有用的文件处理模块,下来好好研究一下

string.ljust(str,len)是用来控制输出格式的

python在挺多情况下挺像c的,不过自己只是初次尝试,程序写的很难看,应该有库可以使之更加简单的,好好学习,加油
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值