python如何匹配正文文中的关键字
时间: 2023-07-05 08:27:55 浏览: 55
Python中可以使用正则表达式模块`re`来匹配正文中的关键字。具体步骤如下:
1. 导入`re`模块。
```python
import re
```
2. 定义要匹配的关键字。
```python
keyword = "Python"
```
3. 读取正文文本。
```python
with open("text.txt", "r") as f:
text = f.read()
```
4. 使用`re`模块中的`search()`函数来查找关键字在文本中的位置。
```python
match = re.search(keyword, text)
```
5. 判断是否找到了关键字,如果找到了,可以通过`start()`和`end()`方法获取关键字在文本中的起始位置和结束位置。
```python
if match:
print("找到了关键字")
print(f"关键字在文本中的起始位置:{match.start()}")
print(f"关键字在文本中的结束位置:{match.end()}")
else:
print("未找到关键字")
```
完整代码如下:
```python
import re
keyword = "Python"
with open("text.txt", "r") as f:
text = f.read()
match = re.search(keyword, text)
if match:
print("找到了关键字")
print(f"关键字在文本中的起始位置:{match.start()}")
print(f"关键字在文本中的结束位置:{match.end()}")
else:
print("未找到关键字")
```
其中,`text.txt`是要匹配的文本文件,可以根据实际情况修改文件名和路径。