python - 以下情况如何正确使用抽象类
问题描述
我正在尝试实现一个代码来纠正给定单词中的小错别字。这些词是来自城市或州列表的专有名词。假设我们知道错字是来自一个城市还是一个州。我正在尝试实现两个类StateTypo
,CityTypo
它们是基类的子类,BaseTypo
.
这是BaseTypo
和的代码StateTypo
:
from collections import Counter
from abc import ABC, abstractmethod
class BaseTypo(ABC):
def __init__(self):
self.WORDS = self.dictionary()
self.N = sum(self.WORDS.values())
@abstractmethod
def dictionary(self):
return dict()
def known(self, words):
""""""
return set(w for w in words if w in self.WORDS)
def P(self, word):
"""Calculate probability of the given word"""
return self.WORDS[word] / self.N
def correction(self, word):
"""Most probable word"""
return max(self.candidates(word), key=self.P)
def candidates(self, word):
""" Generate possible correct words"""
return self.known([word]) or self.known(self.edits1(word)) or self.known(self.edits2(word)) or [word]
def edits1(self, word):
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
inserts = [L + c + R for L, R in splits for c in letters]
return set(deletes + transposes + replaces + inserts)
def edits2(self, word):
return (e2 for e1 in self.edits1(word) for e2 in self.edits1(e1))
class StateTypo(BaseTypo):
def __init__(self):
super(BaseTypo, self).__init__()
self.address = 'states.txt'
def dictionary(self):
print(self.address)
with open(self.address, 'r') as file:
lines = file.readlines()
lines = [line.strip() for line in lines]
return Counter(lines)
if __name__ == '__main__':
a = StateTypo()
corrected = a.correction('himachal prfadesh')
print(corrected) # should ideally print himachal pradesh
但是,上面的代码会遇到以下错误:
Traceback (most recent call last):
File "correctTypo.py", line 59, in <module>
corrected = a.correction('himachal prfadesh')
File "correctTypo.py", line 25, in correction
return max(self.candidates(word), key=self.P)
File "correctTypo.py", line 29, in candidates
return self.known([word]) or self.known(self.edits1(word)) or self.known(self.edits2(w
ord)) or [word]
File "correctTypo.py", line 17, in known
return set(w for w in words if w in self.WORDS)
File "correctTypo.py", line 17, in <genexpr>
return set(w for w in words if w in self.WORDS)
AttributeError: 'StateTypo' object has no attribute 'WORDS'
现在我知道我们真的不需要一个抽象类来实现它,但是考虑到我最初的想法是在基类中保留一个抽象方法,我该如何解决这个问题呢?
解决方案
super
意思是超级,它给你超级对象。
super(StateTypo, self).__init__()
您可以通过or初始化基类BaseTypo.__init__(self)
,但不能super(BaseTypo, self).__init__()
。
并且address
在初始化期间使用,所以它应该是
class StateTypo(BaseTypo):
def __init__(self):
self.address = 'states.txt'
super(StateTypo, self).__init__()
或者您可以更改其他代码以__init__
在第一行保留基类。
推荐阅读
- css - 带有图像的 flex 子项的大小不正确
- vue.js - 如何在测试 vue 组件时为 jest 快照添加样式?
- python - 仅使用 python 读取 csv 文件中的某些行
- c# - 使用 C# 在远程服务器本身上执行批处理文件
- python - 为什么我的 python 脚本没有从命令行运行?
- mysql - 如何解决 GROUP BY 列空优先级?
- javascript - 为什么忽略 AJAX 调用?
- drupal - 使用配置导出创建 Drupal 8 配置文件安装程序
- mod-rewrite - 根据域将example.txt重写为另一个
- c# - 在分配“真实”值之前用空值/空值初始化变量是否有益?