我有两个python列表,一个是关键字列表,另一个是文件名列表。我需要分析基于关键字的文件名列表。我希望python将文件名与关键字匹配,然后根据匹配到的关键字执行操作。在
我看到的是这样的:keywords = ["_CMD_","_COMM_","_RETRANSMIT_"]
file_list = ['2B_CMD_2015.txt','2C_CMD_2015.txt','RETRANSMIT_2015.txt']
for f_name in file_list:
for keyword in keywords:
if keyword in f_name:
#perform operation based on what keyword is matched
else:
#print an error
我遇到的问题是,由于它循环遍历关键字,它会打印一个错误,直到找到文件名中的关键字,然后执行操作,但是我只希望它在搜索的文件名中找不到任何关键字时打印错误。在
我尝试过使用any(),但它似乎在找到匹配项后停止检查文件。例如,使用
^{pr2}$
退货2B_CMD_2015.txt
_CMD_
2B_CMD_2015.txt
_RETRANSMIT_
这是不对的。在
编辑
也尝试过使用regex,但不确定我是否使用了正确的方法:for keyword in keywords:
for item in wordlist:
if re.search(keyword,item) is not None:
print keyword
print item
else:
print "nope"
退货:nope
nope
nope
_CMD_
2B_CMD_2015.txt
_CMD_
2C_CMD_2015.txt
nope
nope
nope
_RETRANSMIT_
_RETRANSMIT_2015.txt
nope
nope
nope
有人能帮我吗?我觉得应该没那么难。在