在记事本中找到某些单词

时间:2013-12-13 07:41:36

标签: python

我的这个程序会在我的记事本文件夹中找到“@@ END DATA”这个词。

问题:如果我的文件夹中包含2个“@@ End DATA”,它将只获得第一个。我怎样才能得到最后一个“@@ End DATA”?只是为了返回结束号码(索引)

def locateEndData(fileTitle):
try:
    filename = fileTitle.split()[-1]
    global end
    f = open(filename,"r")
    with open(filename) as myFile:
        for end, line in enumerate(myFile, 1):
            if '@@END Data' in line:
                return end
    f.close()

档案名称= C:/Users/zhenhui/Desktop/VSM/JDP2270-Hys-IP.VHD

fileTitle = C:/Users/zhenhui/Desktop/VSM/JDP2270-Hys-IP.VHD
locateEndData(fileTitle)

1 个答案:

答案 0 :(得分:0)

假设我s.txt看起来像:

@@END Data
kdawg
@@END Data 

使用正则表达式:

import re

regex = "@@END Data"

def locateEndData(fileTitle):
    try:
        filename = fileTitle.split()[-1]
        with open(filename) as myFile:
            matches = [(m.start(0)+1, m.end(0)+1) for m in re.finditer(regex, myFile.read())]
        return matches[1] #To return the index of the last match
    except:
        print "sorry, dude..."

print locateEndData('s.txt')

输出格式为(start,end)

[(1, 11), (18, 28)]

(1, 11)适用于第一个@@END Data

(18, 28)用于第二个@@END Data