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

Python正则拆分文本仅匹配首个条件,其余列表为空问题求助

问题:正则拆分文本仅单个字段生效,其余字段列表为空

我是编程新手,第一次用re模块写了个split_text函数,想通过正则拆分指定文本,把对应字段内容填充到各自列表里,但现在只有forewing_length列表能填上内容,biostatus等其他列表全是空的。就算不用正则的实现版本也有同样问题。

我的代码

import re

def split_text(text):
    lines = text.split("\n")

    forewing_length = []
    biostatus = []
    distribution_and_frequency = []
    habitat_seasonality_behaviour = []
    life_history = []
    notes = []

    for line in lines:
        match = re.match(r"Forewing length: *(.*?(?=Biostatus|Distribution and frequency|Habitat, seasonality and behaviour|Life history|Notes|$))", line)
        if match:
            forewing_length.append(match.group(1))
        elif line.startswith("Biostatus"):
            match = re.match(r"Biostatus: *(.*?(?=Distribution and frequency|Habitat, seasonality and behaviour|Life history|Notes|$))", line)
            if match:
                biostatus.append(match.group(1))
        elif line.startswith("Distribution and frequency"):
            match = re.match(r"Distribution and frequency: *(.*?(?=Habitat, seasonality and behaviour|Life history|Notes|$))", line)
            if match:
                distribution_and_frequency.append(match.group(1))
        elif line.startswith("Habitat, seasonality and behaviour"):
            match = re.match(r"Habitat, seasonality and behaviour: *(.*?(?=Life history|Notes|$))", line)
            if match:
                habitat_seasonality_behaviour.append(match.group(1))
        elif line.startswith("Life history"):
            match = re.match(r"Life history: *(.*?(?=Notes|$))", line)
            if match:
                life_history.append(match.group(1))
        elif line.startswith("Notes"):
            match = re.match(r"Notes: *(.*)", line)
            if match:
                notes.append(match.group(1))

    return forewing_length, biostatus, distribution_and_frequency, habitat_seasonality_behaviour, life_history, notes

text = "Forewing length: 2.5–3.5 mm. Biostatus: Endemic. Distribution and frequency: Northern North Island, as far south as Hawke’s Bay and Taranaki. Often abundant, but inconspicuous. Habitat, seasonality and behaviour: Native forest, especially podocarp forest. Adults may be found from late November to March. They fly by day in sunshine, settling briefly on ferns and other vegetation, and have been observed swarming around flow- ering nikau palm. Life history: Very poorly known; larvae have been extracted from moss and from rotting wood. Notes: The family Micropterigidae is an extremely ancient lineage, and the adults retain functional mandibles, unlike all other adult moths. These mandibles are used to chew fern spores and pollen. There is a diverse fauna of 19 species in this family in New Zealand; they are found mostly in moist forest. The forewing pattern of shining white markings in Zealandopterix zonodoxa is variable."

split_text(text)

当前输出

(['2.5–3.5 mm. '], [], [], [], [], [])

期望输出

(['2.5–3.5 mm.'],
 ['Endemic.'],
 ['Northern North Island, as far south as Hawke’s Bay and Taranaki. Often abundant, but inconspicuous.'],
 ['Native forest, especially podocarp forest. Adults may be found from late November to March. They fly by day in sunshine, settling briefly on ferns and other vegetation, and have been observed swarming around flow- ering nikau palm.'],
 ['Very poorly known; larvae have been extracted from moss and from rotting wood.'],
 ['The family Micropterigidae is an extremely ancient lineage, and the adults retain functional mandibles, unlike all other adult moths. These mandibles are used to chew fern spores and pollen. There is a diverse fauna of 19 species in this family in New Zealand; they are found mostly in moist forest. The forewing pattern of shining white markings in Zealandopterix zonodoxa is variable.'])

解决方案

核心问题是你用text.split("\n")拆分文本,但输入的text是一整串没有换行的字符串,拆分后lines只有一个元素。循环里第一个match已经匹配了这一行的开头部分,后面的elif条件根本不会触发,导致其他字段列表为空。

另外,原正则里的正向预查逻辑不适合整行匹配,直接针对整个文本匹配各个字段更高效。修改后的代码用字典定义所有字段的匹配规则,逐个提取内容并处理多余空格:

import re

def split_text(text):
    # 定义字段名和对应的正则模式
    field_patterns = {
        "forewing_length": r"Forewing length: *(.*?)(?= Biostatus| Distribution and frequency| Habitat, seasonality and behaviour| Life history| Notes|$)",
        "biostatus": r"Biostatus: *(.*?)(?= Distribution and frequency| Habitat, seasonality and behaviour| Life history| Notes|$)",
        "distribution_and_frequency": r"Distribution and frequency: *(.*?)(?= Habitat, seasonality and behaviour| Life history| Notes|$)",
        "habitat_seasonality_behaviour": r"Habitat, seasonality and behaviour: *(.*?)(?= Life history| Notes|$)",
        "life_history": r"Life history: *(.*?)(?= Notes|$)",
        "notes": r"Notes: *(.*)$"
    }
    
    result = {}
    for field, pattern in field_patterns.items():
        match = re.search(pattern, text, re.DOTALL)
        if match:
            # 去掉内容末尾多余空格,对齐期望输出
            content = match.group(1).rstrip()
            result[field] = [content]
        else:
            result[field] = []
    
    return (result["forewing_length"], result["biostatus"], result["distribution_and_frequency"],
            result["habitat_seasonality_behaviour"], result["life_history"], result["notes"])

text = "Forewing length: 2.5–3.5 mm. Biostatus: Endemic. Distribution and frequency: Northern North Island, as far south as Hawke’s Bay and Taranaki. Often abundant, but inconspicuous. Habitat, seasonality and behaviour: Native forest, especially podocarp forest. Adults may be found from late November to March. They fly by day in sunshine, settling briefly on ferns and other vegetation, and have been observed swarming around flow- ering nikau palm. Life history: Very poorly known; larvae have been extracted from moss and from rotting wood. Notes: The family Micropterigidae is an extremely ancient lineage, and the adults retain functional mandibles, unlike all other adult moths. These mandibles are used to chew fern spores and pollen. There is a diverse fauna of 19 species in this family in New Zealand; they are found mostly in moist forest. The forewing pattern of shining white markings in Zealandopterix zonodoxa is variable."

print(split_text(text))

修改后输出

(['2.5–3.5 mm.'], ['Endemic.'], ['Northern North Island, as far south as Hawke’s Bay and Taranaki. Often abundant, but inconspicuous.'], ['Native forest, especially podocarp forest. Adults may be found from late November to March. They fly by day in sunshine, settling briefly on ferns and other vegetation, and have been observed swarming around flow- ering nikau palm.'], ['Very poorly known; larvae have been extracted from moss and from rotting wood.'], ['The family Micropterigidae is an extremely ancient lineage, and the adults retain functional mandibles, unlike all other adult moths. These mandibles are used to chew fern spores and pollen. There is a diverse fauna of 19 species in this family in New Zealand; they are found mostly in moist forest. The forewing pattern of shining white markings in Zealandopterix zonodoxa is variable.'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:35:29