Python RegEx报告字符串存在的行



我试着写一些东西,很快就会找到一个特定的字符串,并向我报告这些字符串存在的行。我试图找到指数,所以我正在寻找"e+",这只发生在以AAA开头的行上,但并非所有以AAA开头的行都有e+。目前,我的代码看起来像这样:

import re
file = raw_input("Enter a file to scan ")
extfile = file+".txt"
#NDoc = raw_input("Enter a file to place results ")
#log = open (NDoc, 'w')
xfile = open(file+".txt")
expcnt = 0
nl = list

for line in xfile:
        line = line.strip()
        n = re.findall('^PV1.+(e+)')
        if len(n) > 0:
            expcnt = expcnt+1
###            l = line n is on
            nl.append(l)
            for item in nl:
#                log.write(item+"n")


print (expcnt,"exponenets exist and occur on the following lines:"
For item in nl:
        print item
#print ("Your results can be found in",extfile,".") 

基本上,我想知道我需要在带有3个标签(#)的行上放什么,以便记录行n被发现并将其放入列表中。过会儿,我想把这个清单打印出来。顶部的NDoc和log被注释掉了,因为我正在考虑使用from __future__ import print_function将结果打印到一个新页面,但现在可以忽略这一点。因此,我试图将所有行号放入列表nl和所有指数字符串放入列表el(尽管列表el只是为了让我仔细检查事情,以后不会使用)。

任何帮助将不胜感激,提前感谢!

编辑:

import re
file = raw_input("Enter a file to scan ")
extfile = file+".txt"
#NDoc = raw_input("Enter a file to place results ")
#log = open (NDoc, 'w')
xfile = open(file+".txt")
expcnt = 0
nl = list

for line_num, line in enumerate(xfile):
        line = line.strip()
        n = re.findall('^PV1.+(e+)')
        if len(n) > 0:
            expcnt = expcnt+1
            l = line_num
            nl.append(l)
            for item in nl:
#                log.write(item+"n")


#print (expcnt,"exponenets exist and occur on the following lines:"
for item in nl:, does anyone know why that would occur?
    print item
#print ("Your results can be found in",extfile,".")  

由于某些原因,在for itme in nl:

返回错误"Expected an缩进块"

由于您已经逐行读取文件,您可以使用enumerate

for line_num, line in enumerate(xfile):

代替

for line in xfile:

最新更新