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

Python如何逐行遍历列表内多行字符串元素的每行并检测指定内容

解决方法

你存储的contents列表每个元素都是带换行符的多行字符串,使用Python内置的splitlines()方法拆分多行字符串为单行列,再嵌套遍历即可实现逐行检查。

你原有代码存在两个可修正的细节问题:

  • 遍历contents的for语句末尾缺少冒号
  • 没有提前定义start和end变量的取值

完整实现代码如下:

# 定义起止提取标记
start = 'a owl:Class'
end = ' .\n'

contents = []
with open(r'C:/Users/Jupyter Notebooks/small.ttl', 'r', encoding="UTF-8") as f:
    recording = False
    content = ''
    for line in f:
        if start in line:
            recording = True
        if recording and end in line:
            recording = False
            contents.append(content)
        if recording:
            content += line
        else:
            content = ''

# 逐行检查匹配逻辑
target_str = "owl:Class"  # 替换为你需要匹配的目标字符串
for multi_line_content in contents:
    # 拆分多行字符串为独立行
    for line in multi_line_content.splitlines():
        # 若需要忽略行首尾空白符,可改为 if target_str in line.strip()
        if target_str in line:
            print(line)

补充说明:你示例判断逻辑里写的"a:owl Class"和实际文本里的a owl:Class格式不一致,注意匹配的目标字符串要和实际内容格式对齐,避免匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:27:06