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

移除未选中首个选项时的管道符|——脚本逻辑错误修复需求

解决检测字符串构建时多余开头管道符的问题

你需要生成配置文件中detection_pattern键的检测字符串(格式示例:"detect_pattern" = (car|dog|person)),但当前脚本在未选中首个选项时,会生成带多余开头管道符的字符串(比如(|person|truck)),目标是得到正确格式(person|truck)。

当前问题代码:

detectstr="("
print(detectstr)
if inallobj != 'none':
    detectstr +=inallobj
    print(detectstr)
if animals != 'none':
    detectstr += "|"+animals
    print(detectstr)
if humans != 'none':
    detectstr += "|"+humans
    print(detectstr)
if things != 'none':
    detectstr += "|"+things
    print(detectstr)
detectstr +=")"

修复方案

换一种思路:先收集所有非'none'的选项,再用管道符连接,最后包裹括号。这种方式不管哪个选项被选中,都不会出现多余的开头/结尾管道符。

修改后的代码:

# 收集所有有效选项
valid_items = []
if inallobj != 'none':
    valid_items.append(inallobj)
if animals != 'none':
    valid_items.append(animals)
if humans != 'none':
    valid_items.append(humans)
if things != 'none':
    valid_items.append(things)

# 构建检测字符串
detectstr = f"({'|'.join(valid_items)})"
print(detectstr)

说明

  • 先把所有需要加入的检测项放到列表valid_items中,只保留非'none'的内容
  • 用'|'.join(valid_items)自动用管道符连接列表中的元素,只有当列表有多个元素时才会插入管道符,完全避免了手动拼接带来的多余符号问题
  • 最后用f-string把连接后的字符串包裹在()里,生成符合要求的格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:56:03