2015-04-28 13 views
8

ho trovato diversi argomenti di questo e ho trovato questa soluzione:Python rimuovere la punteggiatura da stringa unicode tranne apostrofo

sentence=re.sub(ur"[^\P{P}'|-]+",'',sentence) 

Questo dovrebbe rimuovere ogni punteggiatura ad eccezione', il problema è che si spoglia anche tutto il resto della frase.

Esempio:

>>> sentence="warhol's art used many types of media, including hand drawing, painting, printmaking, photography, silk screening, sculpture, film, and music." 
>>> sentence=re.sub(ur"[^\P{P}']+",'',sentence) 
>>> print sentence 
' 

ovviamente quello che voglio è quello di mantenere la frase senza punteggiatura, e "Warhol" rimane così com'è,

output desiderato:

"warhol's art used many types of media including hand drawing painting printmaking photography silk screening sculpture film and music" 
"austro-hungarian empire" 

Edit: Ho anche provato a utilizzare

tbl = dict.fromkeys(i for i in xrange(sys.maxunicode) 
    if unicodedata.category(unichr(i)).startswith('P')) 
sentence = sentence.translate(tbl) 

ma questo strisce ogni punteggiatura

+0

[qui] (http://stackoverflow.com/questions/21209024/python-regex-remove-all-punctuation-except-hyphen-for-unicode-string) si dice che dovrebbe tutto ciò che è la punteggiatura tranne ' – KameeCoding

+0

Oops, sei corretto; non così esperto nei nuovi costrutti del modulo 'regex'. –

risposta

7

specificare tutti gli elementi che non si desidera rimuovere, vale a dire \w, \d, \s, ecc Questo è ciò che significa l'operatore ^ con tra parentesi quadre. (Partite nulla, tranne)

>>> import re 
>>> sentence="warhol's art used many types of media, including hand drawing, painting, printmaking, photography, silk screening, sculpture, film, and music." 
>>> print re.sub(ur"[^\w\d'\s]+",'',sentence) 
warhol's art used many types of media including hand drawing painting printmaking photography silk screening sculpture film and music 
>>> 
+0

questo funziona per l'apostrofo, come faccio ad aggiungere più eccezioni? come - o qualcosa di simile? – KameeCoding

+0

aggiungi semplicemente '\ -' al' ur "..' –