简体   繁体   English

计数python中的单词类

[英]Count word class in python

I want to create a class which has a function to count the words in a string which is passed through the function as a parameter (is my terminology correct?). 我想创建一个类,该类具有对字符串中的单词进行计数的功能,该字符串作为参数通过该函数传递(我的术语正确吗?)。 This is what I have an it gives me an error "AttributeError: 'str' object has no attribute 'sentence'. 这就是我所拥有的,它给我一个错误“ 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("please count me") myHacks.countWords(“请数我”)

You are mixing the class instantiation with the method call, you should instantiate a class with the correct string 您将类实例化与方法调用混合在一起,应使用正确的字符串实例化一个类

h = myHacks("please count me")

and then call the countWords method on the new object 然后在新对象上调用countWords方法

h.countWords()

It sounds like what you need is just a function, not a class. 听起来您需要的只是一个函数,而不是一个类。 Classes have to be instantiated, and are used when you need to do more than just one operation on a related set of data. 类必须实例化,并且在您需要对一组相关数据进行多个操作时使用。 For your single use case, a function will probably suffice: 对于您的单个用例,一个函数可能就足够了:

def countWords(sentence):
    my_list = []
    counter = 0
    for s in sentence:
        counter += 1
    return(counter)

Also, you never use my_list , and you're counting letters in that sentence, not words. 另外,您永远不要使用my_list ,而是在该句子中计算字母,而不是单词。 This is probably what you need instead: 这可能是您需要的:

def countWords(sentence):
    return len(sentence.split())

In order to use your method, with a class, like you've written, you'd have to call it this way: 为了对类使用您的方法,就像您编写的那样,您必须以这种方式调用它:

hacks = myHacks('this is my sentence')
hacks.countWords()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM