Python:将文件中的单词加载到集合中
我有一个简单的文本文件,其中包含数千个单词,每个单词都在自己的行中,例如,
aardvark
hello
piper
我使用以下代码将单词加载到集合中(我需要单词列表来测试成员资格,因此集合是我选择的数据结构):
my_set = set(open('filename.txt'))
上面的代码生成一个包含以下条目的集合(每个单词后跟一个空格和换行符:
("aardvark \n", "hello \n", "piper \n")
将文件加载到集合中但去掉空格和 \n 的最简单方法是什么?
谢谢
I have a simple text file with several thousands of words, each in its own line, e.g.
aardvark
hello
piper
I use the following code to load the words into a set (I need the list of words to test membership, so set is the data structure I chose):
my_set = set(open('filename.txt'))
The above code produces a set with the following entries (each word is followed by a space and new-line character:
("aardvark \n", "hello \n", "piper \n")
What's the simplest way to load the file into a set but get rid of the space and \n?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
仅删除右侧空格。
To remove only the right hand spaces.
如果你想在Python 2.5中使用它,你需要
If you want to use this in Python 2.5, you need
字符串的 strip() 方法删除两端的空格。
The strip() method of strings removes whitespace from both ends.
只需加载所有文件数据并将其拆分,它将处理每行一个单词或每行用空格分隔的多个单词,并且一次加载整个文件会更快,除非您的文件是 GB 的
Just load all file data and split it, it will take care of one word per line or multiple words per line separated by spaces, also it will be faster to load whole file at once unless your file is in GBs