-2

Is there any other way to do this:

>>> 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']]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
xyz
  • 1
  • 1

1 Answers1

0

You can use a regular expression:

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

Output:

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

The expression looks for words containing one or more (+) letters and possibly a comma ([A-Za-z,]) or (|) a non-whitespace character (\S).

Falko
  • 17,076
  • 13
  • 60
  • 105