Issues with regular_expression

Wiktor

I wrote a script which open multiple text files if line match with specific pattern. After that I would like to compare this line with my country pattern(which contain country names) and (for now) print this country.

(Later I will try to create a method which will move each text file to folder based on it's country)

Basically each of text file contains line :

25/02/2015|11:06:21|MYS|MYS14_FRC6-7_MY1_AA1_WP|MMS1|WXP2632|ashraf|true|120|0|false|

As you can see this example contains country name "MYS"

import os
import string
import re
import sys
import glob
import fileinput

country_pattern = 'MYS','IDN','ZAF', 'THA','TWN','SGP', 'NWZ', 'AUS','ALB','AUT','BEL', 'BGR', 'BIH', 'CHE','CZE', 'DEU', 'DNK', 'ESP','EST','SRB','MDK','MNE','BIH', 'BIH','MNE','FIN', 'FRA', 'GBR','GRC', 'HRV', 'HUN', 'IRL', 'ITA', 'LIE', 'LTU', 'LUX', 'LVA', 'MDA', 'SMR','CYP','NLD','NOR','POL','PRT','ROU','SCG', 'SVK','SVN','SWE','TUR','BRA','CAN','USA','MEX','CHL','ARG','RUS'
pattern = r'(\d+)/(\d+)/(\d+)|(\d+):(\d+):(\d+)|(\S+)|(\S+)|(\S+|(\S+)|(\S+)|(\S+)|(\d+)|(\d+)|(\S+)|'
src = raw_input("Enter source disk location: ")
src = os.path.dirname(src) # zwraca sciezke do pliku
for dir,_,_ in os.walk(src): # odwoluje sie do wielu folderow
file_path = glob.glob(os.path.join(dir,"*.txt")) # szukam plikow mdi
print(file_path)
for file in file_path: 
    f = open(file, 'r')
    object_name = f.readlines()
    f.close()


    for line_name_tmp in object_name: 
        line_name = line_name_tmp.replace('\n','')
        if line_name == '':
            line_name.split()
            continue
        else:
            try:
                re.search(pattern, line_name) 
            except:
                print line_name
                pass

        searchObj = re.search(pattern, line_name) 
        m = searchObj.group(1)
        if m in coutry_pattern:
            print "searchObj.group(1) : ", searchObj.group(1)
        else:
            print 'did not find any'

Unfortunately I get this error:

  File "<string>", line 254, in run_nodebug
  File "C:\Users\kostrzew\Desktop\REPORTS\MdiAdmin.py", line 43, in <module>
  searchObj = re.search(pattern, line_name) #
  File "C:\Python27\Lib\re.py", line 142, in search
    return _compile(pattern, flags).search(string)
  File "C:\Python27\Lib\re.py", line 245, in _compile
    raise error, v # invalid expression
  sre_constants.error: unbalanced parenthesis

I don't know how to solve this error. Did I miss something on pattern?

Kasravnd

You've just omitted one close parenthesis in your regex :

pattern = r'(\d+)/(\d+)/(\d+)|(\d+):(\d+):(\d+)|(\S+)|(\S+)|(\S+|(\S+)|(\S+)|(\S+)|(\d+)|(\d+)|(\S+)|'
                                                               ^

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related