统计一段长文本给定关键词出现的次数,python代码实现
时间: 2023-01-15 22:20:22 浏览: 145
在 Python 中统计一段长文本中给定关键词出现的次数,可以使用 Python 的字符串方法 `count()`。
例如,假设我们想要统计文本中 "apple" 这个词出现的次数,可以使用如下代码:
```python
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 3 times in the text.
```
注意,`count()` 方法是区分大小写的,如果需要忽略大小写,可以将文本和关键词都转换为小写或大写,然后再调用 `count()` 方法。例如:
```python
text = "I have an apple. I like to eat apples. Apple is a fruit."
keyword = "apple"
text = text.lower()
keyword = keyword.lower()
count = text.count(keyword)
print(f"The keyword '{keyword}' appears {count} times in the text.")
```
输出结果如下:
```
The keyword 'apple' appears 3 times in the text.
```
也可以使用正则表达式来忽略大小写,例如:
```python
import re
text = "I have an apple. I like to eat apples. Apple is a fruit."
keyword = "apple"
pattern = re.compile(keyword, re.IGNORECASE)
count = len(pattern.findall(text))
print(f"The keyword '{keyword}' appears {count} times in the text.")
```
输出结果同上。
此外,如果需要统计多个关键词的出现次数,可以使用循环来处理每个关键词,然后累加统计结果即可。
阅读全文