【问题标题】:Calling a function while in another function [duplicate]在另一个函数中调用一个函数[重复]
【发布时间】:2015-07-01 00:09:59
【问题描述】:

我试图在 word_counter 函数中调用 cleanse 函数,但我不知道该怎么做。

这个程序的工作原理是一个字符串通过 cleanse 函数,字符串在 removed_characters 中的任何内容都被删除,然后小写。从那里,我需要在 word_counter 中“调用”已清理的消息,但这是我卡住的地方。我在下面尝试过。

 #how to call this function?
 def cleanse(message):
     cleansed_message = ''  
     remove_characters = "+-=[]"    
     for i in message:
          if i not in remove_characters:
               cleansed_message = cleansed_message + i
          cleansed_message = cleansed_message.lower()
     return cleansed_message

 def word_counter(message):
      # I tried calling the cleansed message here
      message = cleanse(message)
      count = 0
      for i in message:     
           count = len(message.split()) 
      return count

【问题讨论】:

  • 你说得很好。但是,您需要显式调用 word_counter 函数
  • 你是什么意思?来自主函数?
  • 这是工作代码dpaste.com/1E3C7YN.. 以骗子的身份结束问题
  • 当您说要“调用”已清理的消息时,不清楚您的意思。消息是一个字符串,字符串是不可调用的。该字符串是否可能代表您要调用的函数的名称?这是一个微妙但重要的区别。
  • 在 word_counter 函数中,我的目标是观察修改后的字符串是否有意义?

标签: python string function call message


【解决方案1】:
 def word_counter(message):
      message = cleanse(message)
      count = 0
      for i in message:     
           count = len(message.split()) 
      return count

只需将message = cleanse(message) 放在函数定义的顶部(或至少在return count 之前)。您的函数将在返回值时退出,因此之后的所有代码都不会执行。 (请注意,此规则有一些例外,但出于您的目的,可以这样考虑。)然后只需在程序主体中调用 word_counter,如下所示:

print(word_counter("This is my super awesome message!"))

祝你好运!

【讨论】:

    【解决方案2】:
    def cleanse(message):
        cleansed_message = ''  
        remove_characters = "+-=[]"    
        for i in message:
            if i not in remove_characters:
                cleansed_message = cleansed_message + i
                cleansed_message = cleansed_message.lower()
        return cleansed_message
    
    
    def word_counter(message):
    
        message = cleanse(message)
        print(message)
        count = 0
        for i in message:     
            count = len(message.split()) 
        return count
    
    if __name__ == "__main__":
        msg = "Hello + Hye = Hello Hey. Your string has unnecessary characters - so please remove them"
        print(word_counter(msg))
    

    评论:

    您的 word_counter 使用消息字符串调用,如下所示:

    if __name__ == "__main__":
        msg = "Hello + Hye = Hello Hey. Your string has unnecessary characters - so please remove them"
        print(word_counter(msg))
    

    因为 word_counter 是一个函数,它将消息作为参数,然后将该消息传递给 cleanse 函数以清除不必要的字符,将过滤后的输出返回给 word_counter,您可以在其中计算字符串中的单词数并返回计数到调用函数。

    输出

    msg = "Hello + Hye = Hello Hey. Your string has unnecessary characters - so please remove them"
        print(word_counter(msg))
    

    【讨论】:

    • 感谢您格式化代码。
    猜你喜欢
    • 2017-03-07
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多