I have a python code with full explaination of what it does in these questions Scrape text file with Python
Modify python code to include user input search feature
The code I have is compatible with 3.11 version of python and not with 3.8, I am looking to have the logic compatible with 3.8 so I can use that and execute on a server where latest version installed is 3.8
Code
import os
def scrape_ip(txt: str) -> str:
blocks = txt.split('\n\n')
res: list[dict] = []
block: dict = {}
for unparsed in blocks:
tokens = [word for line in unparsed.splitlines() for word in line.split(' ') if word]
match tokens:
case ['Combination', comb, 'Tuple', tup, *_]:
if block:
res.append(block)
block = {'Combination': int(comb[1:]), 'Tuple': int(tup[7:])}
case ['Source', 'Groups:', *ips]:
block['Source Groups'] = ips
case ['Destination', 'IP:', *rest]:
s = ' '.join(rest)
s = s[s.index('Destination Group:') + 19:]
block['Destination Groups'] = s.split(' ')
case ['TCP', '|', port]:
block['Port'] = int(port)
if block:
res.append(block)
return res
def main():
files = [file for file in os.listdir() if file.endswith('.txt')]
res: dict[str: list[dict]] = {}
for file in files:
with open(file, 'r') as f:
txt = f.read()
f_res = scrape_ip(txt)
res[file] = f_res
for file, f_res in res.items():
print(file)
for block in f_res:
for k, v in block.items():
print(f'{k}: {v}')
print()
print()
while search := input('Search For an IP (Enter nothing to exit) \n>>> '):
search_res: list[str] = []
for file, f_res in res.items():
for block in f_res:
if 'Source Groups' in block:
for ip in block['Source Groups']:
if search in ip:
search_res.append(f'{file} - Combination: {block["Combination"]}, Tuple: {block["Tuple"]} - Source Group: {ip}')
if 'Destination Groups' in block:
for ip in block['Destination Groups']:
if search in ip:
search_res.append(f'{file} - Combination: {block["Combination"]}, Tuple: {block["Tuple"]} - Destination Group: {block["Destination Groups"]}')
if search_res:
print('Search Results:')
for result in search_res:
print(result)
else:
print('No Results Found')
if __name__ == '__main__':
main()
Please if anyone can help, that would be great.