Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a list of words after reading a file in python

I have a text file which is named test.txt. I want to read it and return a list of all words (with newlines removed) from the file.

This is my current code:

def read_words(test.txt):
    open_file = open(words_file, 'r')
    words_list =[]
    contents = open_file.readlines()
    for i in range(len(contents)):
         words_list.append(contents[i].strip('\n'))
    return words_list    
    open_file.close()  

Running this code produces this list:

['hello there how is everything ', 'thank you all', 'again', 'thanks a lot']

I want the list to look like this:

['hello','there','how','is','everything','thank','you','all','again','thanks','a','lot']
like image 328
mzn.rft Avatar asked Nov 06 '12 20:11

mzn.rft


People also ask

Which method returns a list of words in python?

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 you read a file and create a list in Python?

You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method.

How do I list the contents of a file in Python?

Python read file into list. To read a file into a list in Python, use the file. read() function to return the entire content of the file as a string and then use the str. split() function to split a text file into a list.


1 Answers

Depending on the size of the file, this seems like it would be as easy as:

with open(file) as f:
    words = f.read().split()
like image 183
mgilson Avatar answered Dec 11 '22 03:12

mgilson