简体   繁体   中英

How to match word in regex -python

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?

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

这是因为re.findall('\\ w +',fitur [0])返回列表['action']尝试使用re.findall('\\ w +',fitur [0])[0]代替

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM