Search a text file and print related lines in Python?

后端 未结 3 1362
长情又很酷
长情又很酷 2020-11-29 21:56

How do I search a text file for a key-phrase or keyword and then print the line that key-phrase or keyword is in?

相关标签:
3条回答
  • 2020-11-29 22:06
    with open('file.txt', 'r') as searchfile:
        for line in searchfile:
            if 'searchphrase' in line:
                print line
    

    With apologies to senderle who I blatantly copied.

    0 讨论(0)
  • 2020-11-29 22:25
    searchfile = open("file.txt", "r")
    for line in searchfile:
        if "searchphrase" in line: print line
    searchfile.close()
    

    To print out multiple lines (in a simple way)

    f = open("file.txt", "r")
    searchlines = f.readlines()
    f.close()
    for i, line in enumerate(searchlines):
        if "searchphrase" in line: 
            for l in searchlines[i:i+3]: print l,
            print
    

    The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

    Or better yet (stealing back from Mark Ransom):

    with open("file.txt", "r") as f:
        searchlines = f.readlines()
    for i, line in enumerate(searchlines):
        if "searchphrase" in line: 
            for l in searchlines[i:i+3]: print l,
            print
    
    0 讨论(0)
  • 2020-11-29 22:28

    Note the potential for an out-of-range index with "i+3". You could do something like:

    with open("file.txt", "r") as f:
        searchlines = f.readlines()
    j=len(searchlines)-1
    for i, line in enumerate(searchlines):
        if "searchphrase" in line: 
            k=min(i+3,j)
            for l in searchlines[i:k]: print l,
            print
    

    Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

    0 讨论(0)
提交回复
热议问题