如何将文件中的所有字符串添加到集合中?

How to add all strings in a file to a set?

大家好(这是针对 python 2.7.12 的)

我正在尝试使用一个包含大约 300,000 个单词的文件,每行一个,然后将它们全部添加到我的 __init__ 方法中的一个集合中,用于我的 class。这是我到目前为止所拥有的。

当我使用除字符串以外的任何参数作为参数时,我无法使用它返回错误的函数。我做错了什么?

我希望集合中只有 'cat'、'car'、'dog' 等每个单词。

    def __init__(self,words):  # accepts a file of strings and puts them into a list
        self.language = set()
        for w in words:
            words.open()
            w.strip('\n')
            self.language.add(w)
        print self.language

如果您有一个名为 data.txt 的文件,您可以将该文件读入一个单词列表,去掉换行符并从名单:

with open('data.txt') as f:
    raw = f.readlines()
words = [i.strip() for i in raw]
wordSet = set(words)

如果你想制作一个 class,你可以将其定义为:

class listOfWords(object):
    """docstring for listOfWords."""
    def __init__(self, wordFile):
        self.wordFile = wordFile
        self.wordSet = self.readfile()

    def readfile(self):
        with open(self.wordFile) as f:
            wordSet = {line.rstrip() for line in f}
        return wordSet

然后创建一个对象:

wordObject = listOfWords('data.txt')

当您想访问您要调用的词集时:

wordObject.wordSet