2013-07-12 5 views
8

ho una stringa:stringa Dividere per interruzione di linea o del periodo con le espressioni regolari in Python

"""Hello. It's good to meet you. 
My name is Bob.""" 

Sto cercando di trovare il modo migliore per dividere questo in una lista divisa per periodi e le interruzioni di linea:

["Hello", "It's good to meet you", "My name is Bob"] 

Sono abbastanza sicuro che dovrei usare le espressioni regolari, ma, non avendo esperienza con loro, sto faticando a capire come farlo.

risposta

17

Non è necessaria la regex.

>>> txt = """Hello. It's good to meet you. 
... My name is Bob.""" 
>>> txt.split('.') 
['Hello', " It's good to meet you", '\nMy name is Bob', ''] 
>>> [x for x in map(str.strip, txt.split('.')) if x] 
['Hello', "It's good to meet you", 'My name is Bob'] 
1
>>> s = """Hello. It's good to meet you. 
... My name is Bob.""" 
>>> import re 
>>> p = re.compile(r'[^\s\.][^\.\n]+') 
>>> p.findall(s) 
['Hello', "It's good to meet you", 'My name is Bob'] 
>>> s = "Hello. #It's good to meet you # .'" 
>>> p.findall(s) 
['Hello', "#It's good to meet you # "] 
+0

In '' "Ciao. # È bello conoscerti #. ' il tuo regex cattura '' ['Ciao', "E 'bello conoscerti #"] '' – eyquem

2

Per esempio, basterebbe dividere sui puntini, eventualmente seguito da spazi bianchi (e di ignorare i risultati vuoti):

>>> s = """Hello. It's good to meet you. 
... My name is Bob.""" 
>>> import re 
>>> re.split(r"\.\s*", s) 
['Hello', "It's good to meet you", 'My name is Bob', ''] 

Nella vita reale, che avrebbe dovuto gestire Mr. Orange, Dr. Greene e George W. Bush, anche se ...

0

È possibile utilizzare questa scissione

re.split(r"(?<!^)\s*[.\n]+\s*(?!$)", s) 
0

Mine:

re.findall('(?=\S)[^.\n]+(?<=\S)',su)