I have two python lists, one of them is a list of keywords, and the other is a list of file names. I need to analyze a list of file names based on the keywords that I have. I want python to match the file name with the keyword, and then perform an operation based on which keyword it matches.
What do I see:
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
The problem I am facing is that since it goes through the keywords, it prints an error until it finds the keyword that is in the file name and then performs the operation, but I want it to print the error, if none of the keywords are found in the name of the file it is looking for.
I tried using any() , but it seems to stop checking files after it finds a match. For example, using
for keyword in keywords: if any(keyword in f_name for f_name in file_list): print f_name print keyword
Returns
2B_CMD_2015.txt _CMD_ 2B_CMD_2015.txt _RETRANSMIT_
This is not true.
Edit Also tried using a regex, but not sure if I am doing this correctly:
for keyword in keywords: for item in wordlist: if re.search(keyword,item) is not None: print keyword print item else: print "nope"
Return:
nope nope nope _CMD_ 2B_CMD_2015.txt _CMD_ 2C_CMD_2015.txt nope nope nope _RETRANSMIT_ _RETRANSMIT_2015.txt nope nope nope
Can anyone help me with this? I feel it shouldn't be that hard.