简体   繁体   中英

How can I add each word in a .txt file to a list in Python?

I want to grab all the words from a .txt file and put them in a list with each word as an element of the list. The words are separated by line breaks in the .txt. My code so far is:

with open('words.txt', "r") as word_list:
    words = list(word_list.read())

However, this piece of code just puts each letter of the .txt as its own element in my list. Any ideas?

with open('words.txt', "r") as word_list:
    words = word_list.read().split(' ')

Get rid of .read() :

words = list(word_list)

Without .read() , you're turning the file handle into a list, which gives you a list of lines. With .read() , you get a big list of characters.

See Here :

ashu='Hello World1'

 ashu.split()

This would split the words based on the spaces between them.

And if you want to split based on any other character instead of space you could do it like

ashu.split('YOUR CHARACTER')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM