[英]Count word class in python
我想创建一个类,该类具有对字符串中的单词进行计数的功能,该字符串作为参数通过该函数传递(我的术语正确吗?)。 这就是我所拥有的,它给我一个错误“ AttributeError:'str'对象没有属性'sentence'。
class myHacks:
def __init__(self, sentence):
self.sentence = sentence
def countWords(self):
my_list = []
my_list = self.sentence.split(" ")
counter = 0
for m in my_list:
counter += 1
return counter
myHacks.countWords(“请数我”)
您将类实例化与方法调用混合在一起,应使用正确的字符串实例化一个类
h = myHacks("please count me")
然后在新对象上调用countWords方法
h.countWords()
听起来您需要的只是一个函数,而不是一个类。 类必须实例化,并且在您需要对一组相关数据进行多个操作时使用。 对于您的单个用例,一个函数可能就足够了:
def countWords(sentence):
my_list = []
counter = 0
for s in sentence:
counter += 1
return(counter)
另外,您永远不要使用my_list
,而是在该句子中计算字母,而不是单词。 这可能是您需要的:
def countWords(sentence):
return len(sentence.split())
为了对类使用您的方法,就像您编写的那样,您必须以这种方式调用它:
hacks = myHacks('this is my sentence')
hacks.countWords()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.