Python 2.7.3:搜索/计算字符串的txt文件,返回整行,该字符串最后出现

Ult*_*rin 1 full-text-search python-2.7

我正在尝试创建一个WiFi日志扫描程序.目前,我们使用CTRL + F和我们的关键字手动浏览日志.我只想自动化这个过程.即在.txt文件中爆炸并接收输出.

我已经掌握了代码的骨头,可以在以后制作它,但我遇到了一个小问题.我希望扫描程序搜索文件(完成),计算该字符串的实例(完成)并输出出现次数(完成),然后输出该字符串最后出现的整行,包括行号(行号不是必需的,只是让事情更容易做一个gestimate,哪个是最近的问题,如果有多个).

目前我正在获取每行中包含字符串的输出.我知道为什么会发生这种情况,我只是想不出一种方法来指定输出最后一行.

这是我的代码:

import os
from Tkinter import Tk
from tkFileDialog import askopenfilename

def file_len(filename):
    #Count Number of Lines in File and Output Result
    with open(filename) as f:
        for i, l in enumerate(f):
            pass     
    print('There are ' + str(i+1) + ' lines in ' + os.path.basename(filename))


def file_scan(filename):
    #All Issues to Scan will go here

    print ("DHCP was found " + str(filename.count('No lease, failing')) + " time(s).")
    for line in filename: 
        if 'No lease, failing' in line:
            print line.strip()

    DNS= (filename.count('Host name lookup failure:res_nquery failed') + filename.count('HTTP query failed'))/2
    print ("DNS Failure was found " + str(DNS) + " time(s).")
    for line in filename: 
        if 'Host name lookup failure:res_nquery failed' or 'HTTP query failed' in line:
            print line.strip()

    print ("PSK= was found " + str(testr.count('psk=')) + " time(s).")
    for line in ln:
        if 'psk=' in line:
            print 'The length(s) of the PSK used is ' + str(line.count('*'))



Tk().withdraw()
filename=askopenfilename()
abspath = os.path.abspath(filename) #So that doesn't matter if File in Python Dir
dname = os.path.dirname(abspath)    #So that doesn't matter if File in Python Dir
os.chdir(dname)                     #So that doesn't matter if File in Python Dir
print ('Report for ' + os.path.basename(filename))
file_len(filename)
file_scan(filename)
Run Code Online (Sandbox Code Playgroud)

那是,相当多,将是我工作的代码(只需要添加一些问题,搜索),我有一个搜索字符串,而不是一个文本文件版本在这里.这输出如下:

Total Number of Lines: 38
DHCP was found 2 time(s).
dhcp
dhcp
PSK= was found 2 time(s).
The length(s) of the PSK used is 14
The length(s) of the PSK used is 8
Run Code Online (Sandbox Code Playgroud)

我只有一般的东西,修改它是一个字符串而不是txt文件,但我正在扫描的字符串将是txt文件中的内容.

不要太担心PSK,我想要列出的所有例子,我会看到如果我可以在稍后阶段将它们整理成一行.

作为旁注,其中很多都是通过以前的搜索混杂在一起,所以我有一个好主意,可能有更简洁的方法来做到这一点.这不是我目前关注的问题,但如果你对这方面有任何建议,请提供解释/链接,说明为什么你的方式更好.我是python的新手,所以我主要处理我目前理解的东西.:)

如果您需要任何进一步的信息,请提前感谢您的帮助,请告知我们.

J4c*_*4cK 7

要搜索和计算我按以下方式解决的字符串事件

'''---------------------Function--------------------'''
#Counting the "string" occurrence in a file
def count_string_occurrence():
    string = "test"
    f = open("result_file.txt")
    contents = f.read()
    f.close()
    print "Number of '" + string + "' in file", contents.count("foo")
        #we are searching "foo" string in file "result_file.txt"
Run Code Online (Sandbox Code Playgroud)