1

I'm trying to design a python function(function_A) which receives two inputs;

Basically, what I'm trying to do is parsing important part from a received sentence(input name : 'sent') according to its type (input name : 'check')

Types are 20 kinds and I have a regular expression for each of them.

For example, if the type of sentence(i.e. check) is 2, it should use regular expression named c2 for parsing sentence;

For example,

c2 = re.compile('(?:sale|sold|provide).*?\sto\s(.*)', re.I|re.S) 

(So I have 20 regular expressions, from c1 to c20)

For the summary, if this function receives type(check) 'n' then, it uses c'n' to parse the sentence.

So, What I've tried up to now is like below:

def newpythonfunction(sent, check):
    c1 = re.compile(~~~)
    c2 = re.compile(~~!@!)
    .....
    c20 = re.compile(!@!@!#!#)
    c_check = 'c' + str(check)
    return c_check.findall(sent)

however, as you might already expect, since c_check is a string, it cannot work as c'n'...

I know I can use 20 if sentences to deal with,

however, I wonder if there any better and efficient(at least just for me writing code) way to make it work!

mij
  • 532
  • 6
  • 13
ChanKim
  • 361
  • 2
  • 16
  • 3
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – quamrana Feb 08 '18 at 09:01

1 Answers1

4

You can use locals()['c{}'.format(check)], but it's better if you just organize your expressions in a proper data structure, like a list or a dict:

c = [
    re.compile(...),
    re.compile(...),
    ...
]
c_check = c[check - 1]
rczajka
  • 1,810
  • 14
  • 13