2017-09-03 2 views
0

Ich habe eine Liste von Begriffen wie folgt:Terminologie in Text enthalten

a 
abc 
a abc 
a a abc 
abc 

ich die Begriffe im Text übereinstimmen soll und ändert ihren Namen als „term1, term2“. Aber ich möchte das längste Match als das richtige Match finden.

Text: I have a and abc maybe abc again and also a a abc. 
Output: I have term1 and term2 maybe term2 again and also a term3. 

Bisher verwendete ich den Code unten, aber es nicht die längste Übereinstimmung finden:

for x in terms: 
    if x in text: 
     do blabla 

Antwort

0

Sie re.sub

import re 

words = ["a", 
"abc", 
"a abc", 
"a a abc" 
] 

test_str = "I have a and abc maybe abc again and also a a abc." 

for word in sorted(words, key=len, reverse=True): 
    term = "\1term%i\2" % (words.index(word)+1) 
    test_str = re.sub(r"(\b)%s(\b)"%word, term, test_str) 

print(test_str) 

verwenden können Sie Ihre „erwarten“ Ergebnis erhalten (Sie haben im Beispiel einen Fehler gemacht)

Input: I have a and abc maybe abc again and also a a abc. 
Output: I have term1 and term2 maybe term2 again and also term4. 
0

oder eine re.sub ersetzen mit der Funktion:

import re 

text = 'I have a and abc maybe abc again and also a a abc' 
words = ['a', 'abc', 'a abc', 'a a abc'] 
regex = re.compile(r'\b' + r'\b|\b'.join(sorted(words, key=len, reverse=True)) + r'\b') 


def replacer(m): 
    print 'replacing : %s' % m.group(0) 
    return 'term%d' % (words.index(m.group(0)) + 1) 

print re.sub(regex, replacer, text) 

Ergebnis:

replacing : a 
replacing : abc 
replacing : abc 
replacing : a a abc 
I have term1 and term2 maybe term2 again and also term4 

oder eine anonyme replacer verwenden:

print re.sub(regex, lambda m: 'term%d' % (words.index(m.group(0)) + 1), text)