2015-04-04 115 views
-2

是否有任何其他方式做到這一點:分割字符串Python的

>>> in_string = "Hello, world! how are you? Your oceans are pretty. Incomplete sentence" 

>>> def sep_words(string_1): 
"""Function which takes a string and returns a list of lists contining the words""" 

     list_1 = string_1.split() 
     list_output = [] 
     list_temp = [] 
    for i in list_1: 
     if ((i[-1] == '!') or (i[-1] == '?') or (i[-1] == '.')): 
      list_temp.append(i[:-1]) 
      list_temp.append(i[-1:]) 
      list_output.append(list_temp) 
      list_temp = [] 
     else: 
      list_temp.append(i) 
    if list_temp == []: 
     pass 
    else: 
     list_output.append(list_temp) 
    print (list_output) 


>>> sep_words(in_string) 

[['Hello,', 'world', '!'], ['how', 'are', 'you', '?'], ['Your', 'oceans', 'are', 'pretty', '.'], ['Incomplete', 'sentence']] 
+2

所以你想在空間分割'''','?'和'.'? – thefourtheye 2015-04-04 05:24:30

回答

0

您可以使用正則表達式:

import re 
message = "Hello, world! how are you? Your oceans are pretty. Incomplete sentence" 
print re.findall(r"[A-Za-z,]+|\S", message) 

輸出:

['Hello,', 'world', '!', 'how', 'are', 'you', '?', 'Your', 'oceans', 'are', 'pretty', '.', 'Incomplete', 'sentence'] 

表達查找包含一個或多個(+)字母和可能的逗號([A-Za-z,])或(|)非空白字符(\S)。