Reputation: 33
How to match word in list when i used demo in https://regex101.com/ it's match with \w+
but when I threw in my code the word not detected, So this is my code:
def MultiTrain(self):
for fitur in self.fiturs:
if (fitur[0] == 'F7') or (fitur[0] == 'F8') or (fitur[0] == 'F9') or (fitur[0] == 'F10') or (
fitur[0] == 'F13') or (fitur[0] == 'F14') or (fitur[0] == 'F15') or (fitur[0] == 'F16') or (
fitur[0] == 'F17') or (fitur[0] == 'F23') or (fitur[0] == 'F24') or (fitur[0] == 'F25') or (
fitur[0] == 'F26') or (fitur[0] == 'F27') or (fitur[0] == 'F28') or (fitur[0] == 'F29') or (
fitur[0] == 'F30') or (fitur[0] == 'F37') or (fitur[0] == re.findall('\w+', fitur[0])) :
print fitur
and this is the word i want to match with regex:
F37,0,1,0,1,1,1,0,1,0,2
F7,0,0,0,0,0,0,1,0,1,0
F11,0,0,1,0,0,1,0,0,0,0
angkasa,1,0,1,0,0,0,0,0,0,0
action,0,1,0,0,0,0,0,0,0,0
acu,0,0,0,0,1,0,0,0,0,0
ampun,0,0,0,0,0,0,0,1,0,0
The output of the program is:
F37,0,1,0,1,1,1,0,1,0,2
F7,0,0,0,0,0,0,1,0,1,0
F11,0,0,1,0,0,1,0,0,0,0
but my expectation is:
F37,0,1,0,1,1,1,0,1,0,2
F7,0,0,0,0,0,0,1,0,1,0
F11,0,0,1,0,0,1,0,0,0,0
angkasa,1,0,1,0,0,0,0,0,0,0
action,0,1,0,0,0,0,0,0,0,0
acu,0,0,0,0,1,0,0,0,0,0
ampun,0,0,0,0,0,0,0,1,0,0
the fitur[0] with word not detected just the F37-F11 How can I fix the regex?
Upvotes: 0
Views: 90
Reputation: 82765
Try.
import re
with open(filename, "r") as infile:
for fitur in infile.readlines():
fitur = fitur.split(',')
if (fitur[0] == 'F7') or (fitur[0] == 'F8') or (fitur[0] == 'F9') or (fitur[0] == 'F10') or (
fitur[0] == 'F13') or (fitur[0] == 'F14') or (fitur[0] == 'F15') or (fitur[0] == 'F16') or (
fitur[0] == 'F17') or (fitur[0] == 'F23') or (fitur[0] == 'F24') or (fitur[0] == 'F25') or (
fitur[0] == 'F26') or (fitur[0] == 'F27') or (fitur[0] == 'F28') or (fitur[0] == 'F29') or (
fitur[0] == 'F30') or (fitur[0] == 'F37') or (fitur[0] == re.findall('\w+', fitur[0])[0]):
print fitur
re.findall('\w+', fitur[0])
returns a list. Try using index to access the first element. Ex: re.findall('\w+', fitur[0])[0]
Just a side note. This would be easier to maintain
if (fitur[0] == ['F7', 'F8', 'F9', 'F10', 'F13', 'F14', 'F23', 'F24', 'F25', 'F26', 'F27', 'F28', 'F29', 'F30', 'F37']) or (fitur[0] == re.findall('\w+', fitur[0])[0]):
print fitur
Upvotes: 1
Reputation: 69
It is because re.findall('\w+',fitur[0]) is returning a list ['action'] try re.findall('\w+',fitur[0])[0] instead
Upvotes: 0