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

Python正则提取hay que后并列动作生成txt文件方案求解

西语hay que句式动作提取脚本修复

原代码正则匹配逻辑存在边界识别错误,无法区分并列动作项与待写入文件的尾部内容,也未兼容特殊结构的动作短语规则,修复后的代码如下:

import re

def fun(x):
    # 定位文本中hay que的位置,提取后续全部内容
    main_match = re.search(r"hay que\s+(.*)", x)
    if not main_match:
        return
    content = main_match.group(1).strip()
    actions = []
    # 匹配动作项:支持普通动词、no+动词、ser+表语、no ser+表语结构,兼容西语特殊字符
    action_pattern = re.compile(r"^((?:no\s+)?(?:ser\s+)?[\wáéíóúñÁÉÍÓÚÑ]+)\s*")
    # 匹配并列分隔符:逗号或单独作连词的y(避免匹配单词内部字符)
    sep_pattern = re.compile(r"^(?:,|y)\s+")

    while True:
        # 提取当前动作项
        act_match = action_pattern.match(content)
        if not act_match:
            break
        current_act = act_match.group(1)
        actions.append(current_act)
        # 截断已匹配的动作部分
        content = content[act_match.end():]
        # 检查后续是否存在并列分隔符,不存在则动作提取结束
        sep_match = sep_pattern.match(content)
        if not sep_match:
            break
        # 跳过分隔符继续匹配下一个动作
        content = content[sep_match.end():]
    
    # 剩余内容为所有动作项对应的公共写入内容
    tail_content = content.strip()
    # 逐个生成文件,动作项空格替换为下划线作文件名
    for act in actions:
        file_name = act.replace(" ", "_") + ".txt"
        with open(file_name, "w", encoding="utf-8") as f:
            f.write(tail_content)

if __name__ == "__main__":
    input_text = input()
    fun(input_text)

匹配规则说明

  • 自动定位文本中任意位置的hay que标识,不受前置文本影响
  • 持续提取并列动作项的判定条件:当前动作项后紧接逗号,或并列连词y,且分隔符后为合法动作开头
  • 动作项兼容普通动词短语、ser开头短语、no/no ser开头的否定短语
  • 动作项提取结束后,剩余所有文本作为公共内容,写入每一个动作项对应的txt文件
  • 文件名自动将动作项内部的空格替换为下划线

测试用例预期结果

  • 输入hay que pintar y decorar las paredes de ese lugar:生成pintar.txt、decorar.txt,两个文件内容均为las paredes de ese lugar
  • 输入hay que pintar y decorar las paredes y los techos:生成pintar.txt、decorar.txt,两个文件内容均为las paredes y los techos
  • 输入hay que correr, saltar y cantar para llegar alli:生成correr.txt、saltar.txt、cantar.txt,三个文件内容均为para llegar alli
  • 输入yo creo que hay que saltar y correr para ir a ese lugar:生成saltar.txt、correr.txt,两个文件内容均为para ir a ese lugar
  • 输入hay que esconderse y ser silenciosos para no ser descubiertos:生成esconderse.txt、ser_silenciosos.txt,两个文件内容均为para no ser descubiertos
  • 输入hay que trabajar, escalar y no temer si quieres llegar a la meta:生成trabajar.txt、escalar.txt、no_temer.txt,三个文件内容均为si quieres llegar a la meta

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 12:12:18