how to go to next line if match is found and again check for the word count in that line

Viewed 71

I am trying to find word count by find a match line if match is found go to next line and count the word in that line

id = open('id.txt','r')
ids = id.readlines()
for i in range(0, len(ids) - 1, 1):
    actual_id = ids[i]
    print(actual_id)
    with open('sample2.txt', 'r') as f:
        for line in f:
            if re.search(r'{actual_id}|RQ', line):
                next_line = line.next()
                if next_line == 'RQ':

                print(line)
                with open('output.txt', 'a') as f:
                    f.write('\n' + line)

Sample.txt text file:

[07-12-2022 13:27:45.728|Info|0189B31C|RQ]
<ServiceRQ><SaleInfo><CityCode Solution=1>BLQ</CityCode><CountryCode Solution=2>NL</CountryCode><CurrencyCode>EUR</CurrencyCode><Channel>ICI</Channel></ServiceRQ>

[07-12-2022 13:27:45.744|Info|0189B31D|RQ]
<ServiceRQ><SaleInfo><CityCode Solution=1>BLQ</CityCode><CountryCode>NL</CountryCode><CurrencyCode>EUR</CurrencyCode><Channel>ICI</Channel></ServiceRQ>

0189B31C

0189B31D

These are unique id's which are store in different text file I am trying to read the 1st id from text file and match that id in Sample.txt and if match is found go to next line and count the number of Solution words and print. Please can someone help me for find the code I am little confused.

2 Answers

I have no experience with the "requests" module. But since no one has answered your question yet, I thought maybe this would suit you. The code should work fine if the number of lines is even. I mean, the code will put strings in the "payload" and do the rest only if there is an entire pair consisting of an odd and an even string.

with open('Sample.txt', 'r') as f:
    while True:
        try:
            odd_line=next(f)
            even_line=next(f)
        except StopIteration:
            break
        #payload=...
        #headers=...
        #response=...
        #print(response.text)

You can use the flag re.DOTALL with the regex {idf}\|RQ.*?</ServiceRQ>, this way the regex matches any character including a newline, and the non-greedy modifier (.*?) part makes sure that few characters as possible will be matched until the string </ServiceRQ> is found. Then, you can use findall to obtain the number of Solution words in the string.

import re

with open('sample2.txt', 'r') as sample_file:
    sample2 = sample_file.read()

id_dict = {}
with open('id.txt', 'r') as id_file:
    for idf in id_file.read().split():
        id_found = re.findall(fr'{idf}\|RQ.*?</ServiceRQ>', sample2, re.DOTALL)
        if id_found:
            solution_found = re.findall('Solution', id_found[0])
            id_dict[idf] = len(solution_found)

print(id_dict)

Output from id_dict

{
    '0189B31C': 2,
    '0189B31D': 1
}
Related