简体   繁体   English

通过python匹配和显示特定行

[英]matching and dispalying specific lines through python

I have 15 lines in a log file and i want to read the 4th and 10 th line for example through python and display them on output saying this string is found : 我在日志文件中有15行,我想例如通过python读取第4行和第10行,并在输出中显示它们,表明找到了此字符串:

abc
def
aaa
aaa
aasd
dsfsfs
dssfsd
sdfsds
sfdsf
ssddfs
sdsf
f
dsf
s
d

please suggest through code how to achieve this in python . 请通过代码建议如何在python中实现这一点。

just to elaborate more on this example the first (string or line is unique) and can be found easily in logfile the next String B comes within 40 lines of the first one but this one occurs at lots of places in the log file so i need to read this string withing the first 40 lines after reading string A and print the same that these strings were found. 只是为了详细说明本示例中的第一个(字符串或行是唯一的),可以在日志文件中轻松找到下一个字符串B出现在第一个字符串的40行之内,但是此行出现在日志文件的很多地方,因此我需要在读取字符串A之后的前40行中读取该字符串,并打印与找到的字符串相同的字符串。

Also I cant use with command of python as this gives me errors like 'with' will become a reserved keyword in Python 2.6. 我也不能with python命令一起使用with因为这给了我类似“ with”的错误,它将成为python 2.6中的保留关键字。 I am using Python 2.5 我正在使用Python 2.5

You can use this: 您可以使用此:

fp = open("file")
for i, line in enumerate(fp):
    if i == 3:
        print line
    elif i == 9:
        print line
        break
fp.close()
#list of random characters
from random import randint
a = list(chr(randint(0,100)) for x in xrange(100))
#look for this
lookfor = 'b'
for element in xrange(100):
    if lookfor==a[element]:
        print a[element],'on',element
#b on 33
#b on 34

is one easy to read and simple way to do it. 是一种易于阅读且简单的方法。 Can you give part of your log file as an example? 您能否以部分日志文件为例? There are other ways that may work better :). 还有其他更好的方法:)。


after edits by author: 经过作者编辑后:

The easiest thing you can do then is: 然后,您可以做的最简单的事情是:

looking_for = 'findthis' i = 1 for line in open('filename.txt','r'):
    if looking_for == line:
        print i, line
    i+=1

it's efficient and easy :) 它既高效又容易:)

def bar(start,end,search_term):
    with open("foo.txt") as fil:
        if search_term in fil.readlines()[start,end]:
            print search_term + " has found" 


>>>bar(4, 10, "dsfsfs")
"dsfsfs has found"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM