Python Comparing Text File - If Else Printing
I have 4 text files in the following formats keycountry.txt UK USA Germany country.txt Brexit - UK USA UK Relations France win world cup keylink.txt www.abc.com www.ddd.com www.e
Solution 1:
Seems like your issue is on one hand related with the for-else construct. Else will always get executed in your code.
Moreover, building upon kaihami's answer, to achieve what you are describing you need to store the matching links/lines in a separate structure like a list and then check if that list is empty to print the matched entries or the string "Not matching", here is my proposed solution:
import re
keycountryfile = "keycountry.txt"
countryfile = "country.txt"withopen('links.txt', 'r') as links:
links_data = [line.strip() for line in links.readlines()]
withopen('keylink.txt', 'r') as keys:
keys_links = set([line.strip() for line in keys.readlines()])
matching_links = []
for url in links_data:
if url in keys_links:
matching_links.append(url)
print('LINKS')
if matching_links:
print('\n'.join(matching_links))
print("matching")
else:
print("Not matching")
print()
withopen(keycountryfile , "r") as f:
country_keys = set(key.lower() for key in
re.findall(r'\w+', f.readline()))
matching_lines = []
withopen(countryfile) as f:
for line in f:
words = set(word.lower() for word in re.findall(r'\w+', line))
if country_keys & words:
matching_lines.append(line.strip())
print("COUNTRY")
if matching_lines:
print('\n'.join(matching_lines))
print("matching")
else:
print("Not matching")
Solution 2:
You can save your results to a list and print the results after finding all matches.
import re
keycountryfile = '''UK USA Germany'''
countryfile = '''Brexit - UK
USA UK Relations
France win world cup'''
links = '''www.abc.com
www.eee.com'''
links_data = links.split()
keys = '''www.abc.com
www.ddd.com
www.eee.com'''
keys_data = keys.split()
keys_split = keys_data
matching_links = []
not_links = []
for url in keys_split:
if url in links_data:
matching_links.append(url)
else:
not_links.append(url)
keys = set(keycountryfile.split())
matching_country = []
not_country = []
for line in countryfile.split():
words = set(word.lower() for word in re.findall(r'\w+', line))
if keys & words:
matching_country.append(line)
else:
not_country.append(line)
print('LINKS')
if matching_links:
print('\n'.join(matching_links))
print("matching")
print("COUNTRY")
print()
if matching_country:
print('\n'.join(matching_country))
print("matching")
print('LINKS')
if not_links:
print('\n'.join(not_links))
print("Not matching")
print("COUNTRY")
if not_country:
print('\n'.join(not_country))
print("Not matching")
You can try this code here
Post a Comment for "Python Comparing Text File - If Else Printing"