我有以下格式的4个文本文件
你知道吗keycountry.txt文件你知道吗
UK USA Germany
你知道吗国家.txt你知道吗
Brexit - UK
USA UK Relations
France win world cup
你知道吗密钥链接.txt你知道吗
www.abc.com
www.ddd.com
www.eee.com
你知道吗链接.txt你知道吗
www.abc.com
www.eee.com
代码:
import re
keycountryfile = "keycountry.txt"
countryfile = "country.txt"
links = open('links.txt', 'r')
links_data = links.read()
links.close()
keys = open('keylink.txt', 'r')
keys_data = keys.read()
keys.close()
keys_split = keys_data.splitlines()
print('LINKS')
for url in keys_split:
if url in links_data:
print(url)
print("matching")
else:
print("Not matching")
keys = set(key.lower() for key in
re.findall(r'\w+', open(keycountryfile , "r").readline()))
print("COUNTRY")
with open(countryfile) as f:
for line in f:
words = set(word.lower() for word in re.findall(r'\w+', line))
if keys & words:
print(line, end='')
print("matching")
else:
print("Not matching")
在代码中print("matching")
重复了多次。我知道因为它在循环中,所以它会重复,print("Not matching")
在没有匹配项时不会显示。我试着将print语句放入循环的内部和外部,但是我无法纠正这个问题。你知道吗
如果输出匹配,则应如下所示:
LINKS
www.abc.com
www.eee.com
matching
COUNTRY
Brexit-UK
USA UK Relations
matching
如果输出不匹配,则应如下所示:
LINKS
Not matching
COUNTRY
Not matching
怎么办?你知道吗
您可以将结果保存到列表中,并在找到所有匹配项后打印结果。你知道吗
你可以试试这个代码here
似乎你的问题一方面与for else结构有关。Else总是在您的代码中执行。你知道吗
此外,基于kaihami的回答,为了实现您所描述的内容,您需要将匹配的链接/行存储在一个单独的结构中,如列表,然后检查该列表是否为空以打印匹配的条目或字符串“Not matching”,下面是我建议的解决方案:
相关问题 更多 >
编程相关推荐