【问题标题】:Count word class in python在python中计算单词类
【发布时间】:2015-01-28 06:25:35
【问题描述】:

我想创建一个类,它具有计算字符串中单词的函数,该字符串作为参数通过函数传递(我的术语是否正确?)。这就是我所拥有的,它给了我一个错误“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("请数我")

【问题讨论】:

  • 就像@JoshSmeaton 说的那样使用collections.Counter,除非你真的想重新发明轮子。
  • str.split 返回一个列表。 内置 函数len 将返回列表中的项目数。无需(显式)使用计数器进行迭代和累积。

标签: python list function class loops


【解决方案1】:

听起来你需要的只是一个函数,而不是一个类。类必须被实例化,并且在您需要对相关数据集执行多个操作时使用。对于您的单个用例,一个函数可能就足够了:

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()

【讨论】:

    【解决方案2】:

    您将类实例化与方法调用混合在一起,您应该使用正确的字符串实例化一个类

    h = myHacks("please count me")
    

    然后在新对象上调用 countWords 方法

    h.countWords()
    

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 2012-08-07
      • 2015-01-07
      • 2021-04-17
      • 2020-10-04
      相关资源
      最近更新 更多