在Python中统计文本中单词的个数可以通过以下步骤实现:
1. 读取文本文件或获取文本内容。
2. 使用`split()`方法将文本分割成单词列表。
3. 使用`len()`函数计算单词列表的长度,即单词个数。
s = "Hello world! This is a sentence."words = s.split() 使用空格分割字符串num_words = len(words) 计算分割后列表的长度print("单词个数:", num_words) 输出单词个数
如果要统计一个文本文件中的单词个数,可以修改上述代码,读取文件内容后再进行分割和计数:

with open('textfile.txt', 'r') as file: 打开文本文件text = file.read() 读取文件内容words = text.split() 使用空格分割文本num_words = len(words) 计算单词个数print("单词个数:", num_words) 输出单词个数
如果需要更复杂的词频统计,例如统计一个文本中出现频率最高的单词,可以使用`collections.Counter`类:
from collections import Counterimport redef count_words(text, n=10):words = re.findall(r'\b\w+\b', text.lower()) 使用正则表达式找到所有单词,并转换为小写word_count = Counter(words) 使用Counter统计词频return word_count.most_common(n) 返回出现频率最高的n个单词及其出现次数示例文本text = "Python is a programming language that lets you work quickly and integrate systems more effectively."统计单词出现频率word_count = count_words(text)for word, count in word_count:print(f"{word}: {count}")
以上代码会输出文本中出现频率最高的10个单词及其出现次数。
请注意,这里的正则表达式`\b\w+\b`用于匹配由单词边界(`\b`)包围的一个或多个字母数字字符(`\w+`),这样可以更准确地识别单词。同时,将文本转换为小写可以确保统计时不区分大小写。
