我正在尝试在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
答案 0 :(得分:0)
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!"))
祝你好运!
答案 1 :(得分:0)
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))