简体   繁体   中英

How to find a text pattern in text file with python?

I need to read a text file and by user interaction, the user enters a pattern for example in this case the user enters ACA , the program reads each line of the text file and the output should be:

  (2) ACACAC
  (0) TGTGTG
 (15) ACACACACACACACACACACACACACACACAC
  (1) TAGACAGTCGATCGACTGCAGCTTCG

In this example text file is:

  ACACAC
  TGTGTG
  ACACACACACACACACACACACACACACACAC
  TAGACAGTCGATCGACTGCAGCTTCG
  CCACCATGGGTGG

My code is (but doesn't work correctly):

fh = open("sequence.txt", "r")
word = input ("enter your word pattern: ")
s = " "
count = 1
while(s):
    s =fh.readline()
    if word in s :
       print("Line{}".format(count),",", s.count(word) , ":", s, end='')
    count +=1

my current output is:

Line1, 1 : ACACAC
Line3, 8 : ACACACACACACACACACACACACACACACAC
Line4, 1 : TAGACAGTCGATCGACTGCAGCTTCG

I suggest you to use re module to search for 'word' in the 'line'. For example you can use re.search to find if there are any matches in a slice of the line, while slicing line with the 'word' length:

import re

word = input ("enter your word pattern: ")
with open("sequence.txt") as fh:
    for line in fh:
        count = 0
        for i in range(len(line)):
            if re.search(l, line[i:i + len(l)]):
            count += 1
        print(f"({count}) {line}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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