Using regex (re.search) in python list
I have the following code
import re
pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']
n = len(pattern)
print pattern
pattern_str = ', '.join(pattern)
print pattern_str
for x in range(0, n):
if re.search(r'\bType I\b', pattern_str):
print "Hello Type I"
elif re.search(r'\bType II\b', pattern_str):
print "Hello Type II"
else:
print "An error has occured"
The required output should be:
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II
But I am not getting the desired result. My current output is:
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Can anyone point out the problem? I suspect it must be related to the str conversion list. I managed to solve the problem using the following code:
for x in pattern:
if re.search(r'\bType I\b', x):
print "Hello Type I"
elif re.search(r'\bType II\b', x):
print "Hello Type II"
else:
print "An error has occured"
But I would like to know why my first code was not working and how I can get it to work. Any help is appreciated
source to share
What you want : Search every line in your list.
What does your code do
re.search(r'\bType I\b', pattern_str)
It searches through pattern_str on each iteration of the loop. What is pattern_str:
pattern_str = ', '.join(pattern)
This way, on each iteration, it looks for the same string, which is the concatenation of the entire list, which always matches the type i in A-minor Type I AGC
.
Going to search for each x
in pattern
does the trick
source to share
You concatenate the entire list into one line and then test that a whole bunch of times. Instead, you should check every line in the list like
for pattern_str in pattern:
if re.search(r'\bType I\b', pattern_str):
print "Hello Type I"
elif re.search(r'\bType II\b', pattern_str):
print "Hello Type II"
else:
print "An error has occured"
so that you search for each pattern, one at a time
source to share
Your template is the same for every iteration. You need to loop through your templates in your loop.
Use for p in pattern
This means that p
there is 'A-minor Type I AGC'
at the first iteration, 'A-minor Type I AGC'
at the second iteration, etc.
import re
pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']
for p in pattern:
if re.search(r'\bType I\b', p):
print "Hello Type I"
elif re.search(r'\bType II\b', p):
print "Hello Type II"
else:
print "An error has occured"
Output:
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II
source to share