Python 在另一个函数中调用函数

Python 在另一个函数中调用函数,python,string,function,call,message,Python,String,Function,Call,Message,我试图在word_counter函数中调用clean函数,但我不知道怎么做 这个程序的工作原理是一个字符串通过cleanse函数,该字符串中所有被删除的字符都被删除,然后被小写。从那里,我需要在word_计数器中“调用”已清除的消息,但这就是我被卡住的地方。我在下面试过了 #how to call this function? def cleanse(message): cleansed_message = '' remove_characters = "+-=[]"

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

这个程序的工作原理是一个字符串通过cleanse函数,该字符串中所有被删除的字符都被删除,然后被小写。从那里,我需要在word_计数器中“调用”已清除的消息,但这就是我被卡住的地方。我在下面试过了

 #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
只需将
message=cleanse(message)
放在函数定义的顶部(或至少在
返回计数之前)。当函数返回值时,它将退出,因此之后的所有代码都不会执行。(请注意,此规则有一些例外,但出于您的目的,可以这样认为。)然后只需在程序体中调用
word\u counter
,如下所示:

print(word\u计数器(“这是我的超级棒的消息!”)

祝你好运

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_计数器,如下所示:

if __name__ == "__main__":
    msg = "Hello + Hye = Hello Hey. Your string has unnecessary characters - so please remove them"
    print(word_counter(msg))
由于word_计数器是一个函数,它将消息作为参数,然后将该消息传递给clean函数以清除不必要的字符,并将过滤后的输出返回到word_计数器,在该计数器中计算字符串中的字数并将计数返回给调用函数

输出

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

你说得很对。但是,您需要明确地调用
word\u计数器
函数您的明确意思是什么?从主函数?以下是工作代码。。当你说你想“调用”已清除的消息时,你不清楚你的意思是什么。消息是一个字符串,不能调用字符串。字符串是否表示希望调用的函数的名称?这是一个微妙但重要的区别。在word_counter函数中,我的目标是观察修改后的字符串(如果有意义的话)?感谢格式化代码。
msg = "Hello + Hye = Hello Hey. Your string has unnecessary characters - so please remove them"
    print(word_counter(msg))