<p>似乎你的问题一方面与for else结构有关。Else总是在<strong>您的<strong>代码中执行。你知道吗</p>
<p>此外,基于kaihami的回答,为了实现您所描述的内容,您需要将匹配的链接/行存储在一个单独的结构中,如列表,然后检查该列表是否为空以打印匹配的条目或字符串“Not matching”,下面是我建议的解决方案:</p>
<pre><code>import re
keycountryfile = "keycountry.txt"
countryfile = "country.txt"
with open('links.txt', 'r') as links:
links_data = [line.strip() for line in links.readlines()]
with open('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()
with open(keycountryfile , "r") as f:
country_keys = set(key.lower() for key in
re.findall(r'\w+', f.readline()))
matching_lines = []
with open(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")
</code></pre>