用Python实现一个函数,输入一段文本,返回其中单词的个数。
发布时间:2023-06-25 08:27:12
以下是使用Python实现计算单词个数的函数:
def count_words(text):
"""
计算文本中单词的个数
:param text: 输入的文本
:return: 单词的个数
"""
# 将文本中的标点符号替换为空格,并将所有字母转换为小写
text = text.lower().replace(",", " ").replace(".", " ").replace("!", " ").replace("?", " ").replace(";", " ").replace(":", " ").replace("-", " ").replace("_", " ").replace("(", " ").replace(")", " ").replace("[", " ").replace("]", " ").replace("{", " ").replace("}", " ").replace("\"", " ").replace("\'", " ").replace("
", " ").replace("\r", " ")
# 分割单词并去重,返回单词个数即可
words = set(text.split())
return len(words)
此函数的实现原理是,先把文本中的标点符号替换为空格,再把文本中的所有字母都转换成小写,这样可以将单词的大小写统一。然后使用 split() 函数将文本分割成单词列表,使用 set() 函数去重,并最终返回单词数量即可。
使用示例:
text = "This is a text, with multiple words. How many words are there in this text? Let's count them!"
word_count = count_words(text)
print("The text contains", word_count, "words.")
输出结果:
The text contains 16 words.
需要注意的是,这个函数计算单词个数的方式可能与不同的计算器不同,因为有些计算器会将字符下划线(_)或连字符(-)连接的单词当做一个单词计算。因此,需要根据具体情况选择是否需要保留这些符号。
