[英]String Counts from dynamic data sets in Python
我的問題與這里的其他人非常相似,但是我沒有找到我想要的確切答案,因此我希望Python的資深用戶能夠進一步幫助我。
我正在為自己的工作學習腳本方法,但是它們不會將我送往培訓中心學習,因此我的首席技術官說我應該學習如何從摘要的Wireshark收集報告中創建日志文件。 我在Bash方面很幸運,但是他希望我能熟練使用Python-在腳本/編程方面沒有任何幫助或背景知識,這是一項艱巨的任務。 我試圖將Wireshark報告中的grep實質上復制到一個新文件中,從而給出DNS流量的發生次數和列表。 唯一的事情是為了有效,它必須能夠在每次使用時使用新的數據集進行工作,否則這將是毫無意義的練習。
>> f1 = open('/home/user/file','r')
>> for line in f1
** if "DNS" in line:
**** print line
兩個問題:
1)如何計算每個DNS發生次數?
2)我將如何管道/打印到新的txt文件?
您可以簡單地初始化一個新變量來計算您的商品
counter = 0
if 'DNS' in line:
counter += 1
print counter
WRT保存數據,您可以使用python進行處理,也可以僅打印出數據並將其輸出到文件中
counter = 0
data = []
if 'DNS' in line:
counter += 1
data.append(line)
to_s = "\n".join(data)
f = open('out.txt', 'w')
f.write(to_s)
f.close()
但是,對於文件處理,這可能會更高級一些,我真的很喜歡做一些生成器流水線!
# this is a generator (an iterable) which only outputs a
# line containing "DNS" if it was requested in an iteration
# furthermore, the way i use a generator here is called "list comprehension"
dns_lines = ( line for line in open('/home/user/file','r') if "DNS" in line )
# the with-statement uses python's magic-methods to take care of
# opening and closing the file
with open("output", 'w') as f:
# enumerate works on generators
# it enumerates each item that is iterated over
# a tuple is returned (count, line)
for count_line in enumerate(dns_lines):
f.write("%d - %s" % (count_line))
David Beazley的更多有關生成器和文件處理的信息
我以為,您想進一步了解python的功能。 因此,我的長篇評論。 :)
//編輯:有關此處將要發生的事情的更多解釋:
我希望這有幫助! 生成器阻止將整個列表加載到內存中,並且它們允許進行許多巧妙的操作和流水線處理。 但是,除了本文中您可以提到的之外,還有很多其他功能!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.