开始使用免费开始使用

Python 中的 RegEx

基于规则的信息抽取对许多 NLP 任务都很有用。某些类型的实体,如日期或电话号码,具有明显的格式,无需训练模型即可通过一组规则识别。本练习将练习在 RegEx 中使用 re 包。目标是在给定的 text 中查找电话号码。

re 包已为您导入。您可以使用 \d 来匹配表示元字符的字符串模式,该元字符可匹配 0 到 9 的任意数字。

本练习是课程的一部分

使用 spaCy 的自然语言处理

查看课程

练习说明

  • 定义一个模式,匹配形如 (111)-111-1111 的电话号码。
  • 使用 re.finditer() 方法查找所有匹配的模式。
  • 对每个匹配项,打印给定 text 中的起始与结束字符位置,以及匹配到的片段。

交互式实操练习

通过完成这段示例代码来试试这个练习。

text = "Our phone number is (425)-123-4567."

# Define a pattern to match phone numbers
pattern = r"\((____){____}\)-(____){____}-(____){____}"

# Find all the matching patterns in the text
phones = re.____(pattern, text)

# Print start and end characters and matching section of the text
for match in phones:
    start_char = match.____
    end_char = match.____
    print("Start character: ", ____, "| End character: ", ____, "| Matching text: ", text[____:____])
编辑并运行代码