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!

1

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot I first thought about making dictionary, however, it would be great! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.