Python: load words from file into a set

…衆ロ難τιáo~ 提交于 2019-11-30 14:30:58

问题


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


回答1:


The strip() method of strings removes whitespace from both ends.

set(line.strip() for line in open('filename.txt'))



回答2:


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

words =  set(open('filename.txt').read().split())



回答3:


my_set = set(map(str.strip, open('filename.txt')))



回答4:


To remove only the right hand spaces.

set(map(str.rstrip, open('filename.txt')))



回答5:


with open("filename.txt") as f:
    s = set([line.rstrip('\n') for line in f])



回答6:


with open("filename.txt") as f:
    mySet = map(str.rstrip, f)

If you want to use this in Python 2.5, you need

from __future__ import with_statement


来源:https://stackoverflow.com/questions/874017/python-load-words-from-file-into-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!