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.

解释:

  1. 首先定义一个正则表达式模式 '[a-zA-Z]+',用于匹配至少一个英文字母。
  2. 将文本按照换行符分割为多个段落。
  3. 对于每个段落,使用 re.search 函数在其中查找是否包含至少一个英文字母。
  4. 如果存在英文字母,就输出该段落。
Python 正则表达式匹配包含英文的段落

原文地址: https://www.cveoy.top/t/topic/nFeq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录