大家好(这是针对python 2.7.12的)
我正在尝试使用一个包含 300,000 个左右单词的文件,每行一个,并将它们全部添加到__init__
我的类方法中的一个集合中。这是我到目前为止。
当我使用字符串以外的任何东西作为参数时,我无法使用它返回错误的函数。我究竟做错了什么?
我希望集合中只有每个单词,例如“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 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句