2016-10-30 1 views
1

J'essaye d'analyser un fichier texte pour faire quelques statistiques à ce sujet en python. Pour ce faire, je souhaite remplacer certaines ponctuations par des jetons. Un exemple d'un tel jeton serait toutes les ponctuations qui terminent une phrase (.!? deviennent <EndS>). J'ai réussi à le faire en utilisant une regex. Maintenant, j'essaye d'analyser les citations. par conséquent, je pense, j'ai besoin d'un moyen de distinguer les citations d'ouverture et les citations de clôture. Je lis le fichier d'entrée ligne par ligne et je n'ai aucune garantie que les devis seront équilibrés.Parsing remplacer des citations

A titre d'exemple:

"Death to the traitors!" cried the exasperated burghers. 
"Go along with you," growled the officer, "you always cry the same thing over again. It is very tiresome." 

devrait être quelque chose comme:

[Open] Death to the traitors! [Close] cried the exasperated burghers. 
[Open] Go along with you, [Close] growled the officer, [Open] you always cry the same thing over again. It is very tiresome. [Close] 

Est-il possible de le faire en utilisant les expressions rationnelles? Y a-t-il une manière plus facile/meilleure de faire ceci?

Répondre

5

Vous pouvez utiliser sous méthode (module re):

import re 

def replace_dbquote(render): 
    return '[OPEN]' + render.group(0).replace('"', '') + '[CLOSE]' 

string = '"Death to the traitors!" cried the exasperated burghers. "Go along with you", growled the officer.' 
parser = re.sub('"[^"]*"', replace_dbquote, string) 

print(parser) 

https://docs.python.org/3.5/library/re.html#re.sub