【发布时间】:2018-08-09 21:51:04
【问题描述】:
我有 4 个以下格式的文本文件
keycountry.txt
UK USA Germany
国家/地区.txt
Brexit - UK
USA UK Relations
France win world cup
keylink.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") 在没有匹配项时不会显示。我尝试将打印语句放在循环内部和外部,但我无法解决问题。
如果匹配,输出应该是这样的:
LINKS
www.abc.com
www.eee.com
matching
COUNTRY
Brexit-UK
USA UK Relations
matching
如果不匹配,输出应该是这样的:
LINKS
Not matching
COUNTRY
Not matching
如何解决这个问题?
【问题讨论】:
-
最好的方法是调试你的脚本,有一个名为
pdb的内置工具,或者在一些fance IDEs中,调试器也是内置的,使用起来简单有趣.
标签: python for-loop if-statement