简体   繁体   English

如何将.txt文件中的每个单词添加到Python列表中?

[英]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. 我想从.txt文件中获取所有单词,然后将它们放在列表中,每个单词都作为列表的元素。 The words are separated by line breaks in the .txt. 单词由.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. 但是,这段代码只是将.txt的每个字母作为自己的元素放在我的列表中。 Any ideas? 有任何想法吗?

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

Get rid of .read() : 摆脱.read()

words = list(word_list)

Without .read() , you're turning the file handle into a list, which gives you a list of lines. 没有.read() ,您.read()文件句柄变成一个列表,从而为您提供行列表。 With .read() , you get a big list of characters. 使用.read() ,您可以获得大量字符。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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