2010-06-14 6 views
3

J'ai un fichier texte qui contient des données dans les balises {[]}. Quel serait le moyen suggéré pour analyser ces données afin que je puisse simplement utiliser les données à l'intérieur des balises?Analyse des éléments à partir du fichier texte

Exemple de fichier texte ressemblerait à ceci:

«c'est un tas de texte qui n'est pas {[vraiment]} utile dans tout {[façon]}. Je dois {{obtenir}} des éléments {[de]} ça. '

Je voudrais finir avec 'vraiment', 'manière', 'obtenir', 'de' dans une liste. Je suppose que je pourrais utiliser split pour le faire .. mais il semble qu'il pourrait y avoir un meilleur moyen de sortir. J'ai vu une tonne de bibliothèques d'analyse, y en a-t-il une qui serait parfaite pour ce que je veux faire?

Répondre

6

J'utiliserais des expressions régulières. Cette réponse suppose qu'aucun des caractères de la balise {} [] n'apparaît dans les autres balises.

import re 
text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' 

for s in re.findall(r'\{\[(.*?)\]\}', text): 
    print s 

Utilisation du mode bavard dans les expressions régulières python:

re.findall(''' 
    \{ # opening curly brace 
    \[ # followed by an opening square bracket 
    ( # capture the next pattern 
    .*? # followed by shortest possible sequence of anything 
    ) # end of capture 
    \] # followed by closing square bracket 
    \} # followed by a closing curly brace 
    ''', text, re.VERBOSE) 
3

Ceci est un emploi pour regex:

>>> import re 
>>> text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' 
>>> re.findall(r'\{\[(\w+)\]\}', text) 
['really', 'way', 'get', 'from'] 
+0

Wow, c'était rapide .. et parfait. Merci! – chris

+2

@chris: soyez prudent avec ceci: il capture uniquement les caractères alphanumériques entre les délimiteurs. Si vos données ont d'autres sortes de caractères, cela ne les ramassera pas. –

+2

Pour exposer le commentaire de Bryan, les cas spécifiques de: mots césure, {[anti-guerre]}; mots composés avec des espaces, {[New England]}; noms de lieux ou de personnes qui utilisent la ponctuation et les espaces, {[Boston, MA]}, {[George W. Bush]}. – tgray

2

plus lent, plus gros, pas expresions régulièrement

l'ancien manière scolaire: P

def f(s): 
    result = [] 
    tmp = '' 
    for c in s: 
     if c in '{[': 
      stack.append(c) 
     elif c in ']}': 
      stack.pop() 
      if c == ']': 
       result.append(tmp) 
       tmp = '' 
     elif stack and stack[-1] == '[': 
      tmp += c 
    return result 

>>> s 
'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' 
>>> f(s) 
['really', 'way', 'get', 'from'] 
1

Une autre façon

def between_strings(source, start='{[', end=']}'): 
    words = [] 
    while True: 
     start_index = source.find(start) 
     if start_index == -1: 
      break 
     end_index = source.find(end) 
     words.append(source[start_index+len(start):end_index]) 
     source = source[end_index+len(end):] 
    return words 


text = "this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it." 
assert between_strings(text) == ['really', 'way', 'get', 'from']