Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of string sentences to words

I'm trying to essentially take a list of strings containg sentences such as:

sentence = ['Here is an example of what I am working with', 'But I need to change the format', 'to something more useable']

and convert it into the following:

word_list = ['Here', 'is', 'an', 'example', 'of', 'what', 'I', 'am',
'working', 'with', 'But', 'I', 'need', 'to', 'change', 'the format',
'to', 'something', 'more', 'useable']

I tried using this:

for item in sentence:
    for word in item:
        word_list.append(word)

I thought it would take each string and append each item of that string to word_list, however the output is something along the lines of:

word_list = ['H', 'e', 'r', 'e', ' ', 'i', 's' .....etc]

I know I am making a stupid mistake but I can't figure out why, can anyone help?

like image 896
George Burrows Avatar asked Dec 12 '11 17:12

George Burrows


People also ask

How do you change a string sentence into a list of words?

How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

What does the split () method return from a list of words?

Description. Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

How do I convert a list to a string in one line?

To convert a list to a string in one line, use either of the three methods: Use the ''. join(list) method to glue together all list elements to a single string. Use the list comprehension method [str(x) for x in lst] to convert all list elements to type string.


1 Answers

You need str.split() to split each string into words:

word_list = [word for line in sentence for word in line.split()]
like image 66
Sven Marnach Avatar answered Oct 10 '22 00:10

Sven Marnach