因此,我知道以前已经有人问过这个问题,但是我找不到我的问题的答案,所有的答案都让我更加困惑。
因此,我创建了一个名为Books的类,该类将文件的位置和文件名作为输入,并具有一种称为countwords的方法,该方法可对文件的单词进行计数。
我创建了此类的一堆实例(它们被称为吗?),但我不想在所有实例上迭代CountWords方法。这是我的代码:
class Books():
def __init__(self, path, fullname):
self.path = path
self.fullname = fullname
def count_words(self):
try:
with open(self.path + self.fullname, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {self.fullname} doesn't exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {self.fullname} has about {num_words}"
f"words.")
alice = Books("text_files/", 'alice.txt')
siddharta = Books("text_files/", 'siddhartha.txt')
mobydick = Books('text_files/', 'moby_dick.txt')
little_women = Books('text_files/', 'little_women.txt')
我不会写这样的东西:
for book in Books.list():
book.count_words()
并获得:
The file alice.txt has about 29465 words.
The file siddhartha.txt has about 1500 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.
打印与Books()类关联的所有实例的单词计数,如何实现呢?谢谢!
编辑:我尝试了不同的方法,但这是我现在正在使用的一种:
码:
# 1
import weakref
class Book():
# 2
book_list = []
def __init__(self, path, fullname):
self.path = path
self.fullname = fullname
# 3
self.__class__.book_list.append(weakref.proxy(self))
def count_words(self):
try:
with open(self.path + self.fullname, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {self.fullname} doesn't exist.")
else:
words = contents.split()
num_words = len(words)
print(f"The file {self.fullname} has about {num_words} "
f"words. ")
alice = Book("text_files/", 'alice.txt')
siddharta = Book("text_files/", 'siddhartha.txt')
mobydick = Book('text_files/', 'moby_dick.txt')
little_women = Book('text_files/', 'little_women.txt')
# 4
for book in Book.book_list:
book.count_words()
而不必所有已创建的实例类保持引用,我建议你定义你的数据第一,然后创建从数据实例的集合。
例如:
book_paths = [('text_files/', 'alice.txt'),
('text_files/', 'siddharta.txt'),
('text_files/', 'moby_dick.txt'),
('text_files/', 'little_women.txt')]
books = []
for path, name in book_paths:
book = Books(path, name)
books.append(book)
book.count_words()
您还可以稍后进行迭代books
以执行所需的任何操作。使用list
理解的另一种方法:
books = [Books(path, name) for path, name in book_paths]
for book in books:
book.count_words()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句