使用python写脚本之练习二
需求:
1) 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
2)读取ips.txt文件统计这个文件中ip出现频率排前10的ip
题目是在其他博主的文章上看见的,下面会分享python写的和shell写的版本,带注释。
- 原作者的版本
原作者的版本没有很多注释,我复制在这里,加了一些详细的注释,方便大家理解。
版本一
import random
f = open('ips.txt','a+') #打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
for i in range(1200):
f.write('172.25.254.' + str(random.randint(1,255)) + '\n') # 使用random生成IP最后一段,并组合成完整IP写入文件
f.seek(0)
"""
f.seek(偏移量,[起始位置]):用来移动文件指针。
偏移量: 单位为字节,可正可负
起始位置: 0 - 文件头, 默认值; 1 - 当前位置; 2 - 文件尾
对一个空文件写后再读时候,应在写完之后seek(0),使指针回到文件开头以便再读
"""
d = {
} # 定义一个空字典,用来存放结果
for i in f.readlines(): # 逐行读取文件
if i in d: # 如果IP已经在字典中,那么其对应的值加1
d[i]+=1
else:
d[i]=1 # 如果IP不在字典中,那么加入字典,且赋值为1
sort = sorted(d.items(),key=lambda x:x[1],reverse=True)[:10] # sorted()返回一个列表 [:10]对列表进行切片,去前面10个元素
# items() 它返回一个键 — 值对列表,即 [(k,v),(k,v),(k,v)]
# key=lambda x:x[1] (k,v)是一个元组,意思是以 v 为依据进行排序
"""
sorted(iterable, key=None, reverse=False)
iterable -- 可迭代对象。
key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
key是sorted()函数最强大的组成部分之一。这个参数可以接收一个函数,该函数将作用于排序列表中的每个值,以确定结果的顺序
"""
for i in sort:
print(i[0]) # 输出前十的IP
版本二
import random
def create_ip_file(filename):
ip =['172.25.254.' + str(i) for i in range(0,255)] # 生成了一个有 255 个IP的列表 0-254
with open(filename,'a+') as f:
for count in range(1200):
f.write(random.sample(ip,1)[0] + '\n') # 写入IP
# random.sample(ip,1) 表示从ip列表中随机取一个IP,返回依然是个列表,所以需要取出来 [0]
create_ip_file('ips.txt')
def sorted_by_ip(filename,count=10):
ips_dict = dict()
with open(filename) as f: # 后面的部分与上一个方法就是大同小异了,只是读取文件的方式不同,其他思路都是一样
for ip in f:
if ip in ips_dict:
ips_dict[ip] += 1
else:
ips_dict[ip] = 1
sorted_ip = sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:count]
return sorted_ip
print(sorted_by_ip('ips.txt'))
- 我的python版本
from random import randint
from collections import Counter
ipFore = "172.25.254."
fileName = "ips.txt"
def writeIP(num):
"""
:param num: the number of ip which will be writen in file
:return:
"""
for i in range(0,num):
ipEnd = str(randint(0,255))
fullIP = ipFore + ipEnd
with open(fileName,'a') as ips:
ips.write(fullIP + "\n")
def staticIP(num):
"""
:param num: show most common IP
:return:
"""
allIP = []
with open(fileName) as ips:
for ip in ips:
allIP.append(ip.rstrip())
result = Counter(allIP)
print(result.most_common(num))
writeIP(1200)
staticIP(10)
- 我的shell版本
#!/usr/bin/env bash
:<<!
1) 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip;
2) 读取ips.txt文件统计这个文件中ip出现频率排前10的ip
!
# 生成文件
ipFore="172.25.254."
for i in {
1..1200};do
ipEnd=$[ $RANDOM % 256 ] # 随机产生IP的最后一个段 0-255
echo ${
ipFore}${
ipEnd} >> ips.txt # 组合成完整的IP,写入文件
done
# 统计文件中出现频率前十的IP
awk '{count[$0]++}END{for(i in count){print count[i],i}}' ips.txt | sort -nr | head -10
以上就是本次练习的解决方案,思路不唯一,欢迎交流。