在 Python 中统计一段长文本中给定关键词出现的次数,可以使用 Python 的字符串方法 count()
。
例如,假设我们想要统计文本中 "apple" 这个词出现的次数,可以使用如下代码:
text = "I have an apple. I like to eat apples. Apple is a fruit."
keyword = "apple"
count = text.count(keyword)
print(f"The keyword '{keyword}' appears {count} times in the text.")
输出结果如下:
The keyword'apple' appears