2017-09-03 4 views
0

J'ai une liste de termes comme suit:Terminologie correspondant dans le texte

a 
abc 
a abc 
a a abc 
abc 

Je veux faire correspondre les termes dans le texte et modifie leur nom comme « terme1, terme2 ». Mais je veux trouver le match le plus long comme le match correct.

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. 

Jusqu'à présent, j'utilisé le code ci-dessous, mais il ne trouve pas le match le plus long:

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

Répondre

0

Vous pouvez utiliser 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) 

Il obtiendra le résultat « attendre » (vous avez fait une erreur dans l'exemple)

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

ou en utilisant un re.sub remplacer la fonction:

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) 

résultats:

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

ou utiliser un substitut anonyme:

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