I want to count the occurrences of a multi line ASCII pattern within a file.
The pattern looks like this:
a1 b2 c3
The file I want to search looks like this: (The _ represent whitespaces but I thought it's easier to understand with this notation)
_ _ _ a1 _ _ _ b2 _ _ _ c3 _ _ _ _ a1 a1_ _ _ _ _ _ _ _ b2 _ _ _ _ a1 _ _ _ _ _ _ _ _ _ c3 _ _ _ _ b2 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ c3
The desired output should be 3 in this case. I solved this with a bunch of loops and counting symbols till finding the first part of the pattern. Then checking if the second part hast the same count of numbers before to ensure the second part is underneath the first one and so on.
_ _ _ _ a1 _ _ _ a1 _ _ _ _ b2 _ _ b2 _ _ _ _ _ c3 _ _ _ c3
In this example there is only one valid pattern found since the parts of the second aren't exactly under each other.
The regarding code is as following:
import sys def load_data(path): data =  try: fp = open(path, 'r') for f_line in fp: data.append(f_line.rstrip()) finally: fp.close() return data bug_path = 'data/bug.txt' landscape_path = 'data/landscape.txt' bug = load_data(bug_path) landscape = load_data(landscape_path) findings = [ for x in landscape] min_len_bug = min([len(x) for x in bug]) for cnt, l_line in enumerate(landscape): if len(l_line) < min_len_bug: continue for bCnt, bLine in enumerate(bug): findings[cnt] = [(bCnt, ind) for ind in range(len(l_line)) if l_line.startswith(bLine, ind)] + findings[cnt] def bugInLine(line, bug_part, whitespace): for entry in line: if entry == bug_part and entry == whitespace: return True complete_bugs_cnt = 0 for cnt, l_line in enumerate(findings): for found in l_line: if found == 0 and len(findings) > (cnt + len(bug) - 1): check = 1 for i in range(1, len(bug)): if bugInLine(findings[cnt + i], i, found): check = check + 1 if check == len(bug): complete_bugs_cnt = complete_bugs_cnt + 1 print complete_bugs_cnt
Since this isn't the most elegant solution I'm wondering if there is a possibility to solve this problem by using some regex code and combine this with the
I'd highly appreciate any help.