数一数字符串中的单词数?

2024-04-19 20:01:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这个函数。

# Function to count words in a string.
def word_count(string):
    tokens = string.split()
    n_tokens = len(tokens)
    print (n_tokens)

# Test the code.
print(word_count("Hello World!"))
print(word_count("The quick brown fox jumped over the lazy dog."))

但结果是

2
None
9 
None

而不是仅仅

2
9

Tags: theto函数innonestringlendef
2条回答

除了布赖恩所说的,这段代码还演示了如何得到你想要的:

# Function to count words in a string.
def word_count(string):
    tokens = string.split()
    n_tokens = len(tokens)
    return n_tokens     # <-- here is the difference

print(word_count("Hello World!"))
print(word_count("The quick brown fox jumped over the lazy dog."))

word_count没有return语句,因此它隐式返回None。您的函数打印令牌的数量print (n_tokens),然后您的函数调用print(word_count("Hello World!"))打印None

相关问题 更多 >