Python 正则表达式匹配包含英文的段落
Python 正则表达式匹配包含英文的段落
以下 Python 代码示例展示如何使用正则表达式匹配包含英文的段落:
import re
text = 'This is a paragraph with English words.
这是一段中文。
Another paragraph with more English words.'
pattern = re.compile(r'[a-zA-Z]+') # 匹配英文字母
paragraphs = text.split('
')
for p in paragraphs:
if re.search(pattern, p):
print(p)
输出:
This is a paragraph with English words.
Another paragraph with more English words.
解释:
- 首先定义一个正则表达式模式
'[a-zA-Z]+',用于匹配至少一个英文字母。 - 将文本按照换行符分割为多个段落。
- 对于每个段落,使用
re.search函数在其中查找是否包含至少一个英文字母。 - 如果存在英文字母,就输出该段落。
原文地址: https://www.cveoy.top/t/topic/nFeq 著作权归作者所有。请勿转载和采集!