2012-05-23 20 views
6

ho una stringa del tipo:prefisso corrispondente in pitone

" This is such an nice artwork" 

e ho un tag_list ["art","paint"]

Fondamentalmente, voglio scrivere una funzione che accetta questa stringa e taglist come ingressi e mi ritorna la parola "opera d'arte" come opera d'arte contiene la parola arte che è nella taglist.

Come faccio a farlo nel modo più efficiente?

Voglio che questo per essere efficiente in termini di velocità

def prefix_match(string, taglist): 
     # do something here 
    return word_in string 

risposta

7

provare quanto segue:

def prefix_match(sentence, taglist): 
    taglist = tuple(taglist) 
    for word in sentence.split(): 
     if word.startswith(taglist): 
      return word 

Questo funziona perché str.startswith() può accettare una tupla di prefissi come argomento.

Nota che ho rinominato string in sentence quindi non c'è alcuna ambiguità con il modulo stringa.

+0

hey @andrew, come se voglio restituire la stringa di non taglist la parola? – indi60

2

Prova questo:

def prefix_match(s, taglist): 
    words = s.split() 
    return [w for t in taglist for w in words if w.startswith(t)] 

s = "This is such an nice artwork" 
taglist = ["art", "paint"] 
prefix_match(s, taglist) 

È possibile che questo restituirà un elenco con tutte le parole del stringa che corrispondono a un prefisso nella lista dei tag.

1

Ecco una possibile soluzione. Sto usando regex, perché in questo modo posso eliminare facilmente i simboli di punteggiatura. Inoltre, sto usando collections.Counter questo potrebbe aggiungere efficienza se la tua stringa ha un sacco di parole ripetute.

tag_list = ["art","paint"] 

s = "This is such an nice artwork, very nice artwork. This is the best painting I've ever seen" 

from collections import Counter 
import re 

words = re.findall(r'(\w+)', s) 

dicto = Counter(words) 

def found(s, tag): 
    return s.startswith(tag) 

words_found = [] 

for tag in tag_list: 
    for k,v in dicto.iteritems(): 
     if found(k, tag): 
      words_found.append((k,v)) 

L'ultima parte può essere fatto con la lista di comprensione:

words_found = [[(k,v) for k,v in dicto.iteritems() if found(k,tag)] for tag in tag_list] 

Risultato:

>>> words_found 
[('artwork', 2), ('painting', 1)]