You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas提取Example与Constraints间文本遇返回Null问题求助

提取Example与Constraints之间文本的解决方案

问题场景

需要从Pandas数据框的单行文本中,提取Example与Constraints之间的所有内容,示例文本如下:

"Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You can return the answer in any order.
 Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
 Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
 Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?"

原有代码返回Null:

def extract(example):
    return example.str.extract('(Example.*(?=.Constraints))')

问题原因

  1. 正则默认.不匹配换行符,Example.*只能匹配同一行内容,无法覆盖跨多行的示例文本。
  2. 正向预查(?=.Constraints)写法错误:原文本中Constraints前是空格而非任意字符,且未处理换行场景。
  3. 贪婪匹配.*可能导致匹配范围超出预期(此处因换行问题已失效)。

解决方法

启用正则的DOTALL模式(让.匹配换行符),使用非贪婪匹配并准确匹配Constraints的前置空格,修改后的代码如下:

def extract(example):
    # (?s) 启用DOTALL模式,.*? 非贪婪匹配,(?=\sConstraints) 匹配带前置空格的Constraints作为终止符
    return example.str.extract('(?s)(Example.*?)(?=\\sConstraints)')

说明

  • (?s):等价于re.DOTALL,让正则中的.可以匹配包括换行在内的所有字符。
  • .*?:非贪婪匹配,确保匹配到第一个\sConstraints时停止,避免过度匹配。
  • (?=\sConstraints):正向预查,匹配带有前置空格的Constraints字符串,作为提取内容的终止标记。

内容的提问来源于stack exchange,提问作者Emm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 02:30:50