jeudi 28 juillet 2016

Best way to avoid copy-paste and hardcoding

' Hello, SO community.

Problem: I have many regEx patterns, such as

r'to.*school', r'built.*in'

and etc. In every case, I should execute a code, that varies from situation to situation.

Example: If pattern is 'to.*school', I want to find the verb before 'to' and that's why I write something like:

for num, part in enumerate(sentence):
    if part == 'to':
        result = sentence[num-1]

If pattern is 'built.*in', I want to find the time and that's why I write something like:

for num, part in enumerate(sentence):
    if part == 'in':
        result = sentence[num+1]

So there's the problem - how can I avoid copy-pasting code, if there's over 500 patterns and each pattern has its own way to get result?

My thoughts: I understand it should be some kind of database, which stores patterns and solutions, but how do I execute solution, if it's a string? I'm totally lost.

Aucun commentaire:

Enregistrer un commentaire