我有一個文本文件,名爲test.txt
。我想閱讀它並從文件中返回所有單詞的列表(刪除了換行符)。在閱讀python文件後返回單詞列表
這是我當前的代碼:
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()
運行該代碼會產生這個名單:
['hello there how is everything ', 'thank you all', 'again', 'thanks a lot']
我想要列表如下所示:
['hello','there','how','is','everything','thank','you','all','again','thanks','a','lot']
http://docs.python.org/2/library/stdtypes.html#str。split – kreativitea