尝试使用从父类匹配调用方法titleMatch
的子类isWordIn
来查找关键字是否在标题中。
我想要的text
参数似乎最终成为关键字(请参阅输出。)此代码的大多数设计都受到练习的限制,但我想我已经尝试过各种方式(但是正确的:))
显然缺少一些非常基本的(无疑是主要的)继承概念。
import string
class abstractBaseClass(object):
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
raise NotImplementedError
class match(abstractBaseClass):
'''
get word to match
isWordIn breaks text into lower case list of words, tries word against list
'''
def __init__(self, word):
self.word = word
def isWordIn(self, text):
self.text = text
newText = ''
for char in range(len(self.text)):
if self.text[char] in string.punctuation:
char = ' '
newText += char
else:
char = self.text[char]
newText += char
lowerText = newText.lower()
chopText = lowerText.split(' ')
print 'self.word: ' + self.word.lower()
return self.word.lower() in chopText
class titleMatch(match):
'''
find word in title
'''
def evaluate(self, titl):
self.titl = titl
return self.isWordIn(self.titl)
title = 'Red Badge of Courage'
abstract = 'foo'
text = 'some long string'
test = match('RED')
print test.isWordIn(title)
test2 = titleMatch(title)
print test2.evaluate(title)
结果:
%run "c:\docume~1\winuser\locals~1\temp\tmpvrnfcj.py"
self.word: red
True
self.word: red badge of courage
False
答案 0 :(得分:1)
这似乎是一种非常复杂的做法:
>>> word = 'red'
>>> string = 'red badge of courage'
>>> word in string
True
Python不是Java,你不需要把所有东西放在一个类中,事实上你可能在Python中大部分时间都不需要一个类。一个好的经验法则是,如果一个类只有2个方法,其中一个是__init__()
,那么你就不需要它了。
答案 1 :(得分:0)
也许你打算用这种方式初始化test2
?:
test2 = titleMatch('RED')