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

如何从含方括号内逗号的字符串提取值并实例化Rule类

问题描述

我用这段代码读取文件:

def readFile():
    file = open('Rules.txt', 'r')
    lines = file.readlines()
    for line in lines:
        rulesList.append(line)

得到的rulesList是:

['\n', "Rule(F1, HTTPS TCP, ['ip', 'ip'], ['www.google.ca', '8.8.8.8'], 443)\n", '\n', "Rule(F2, HTTPS TCP, ['ip', 'ip'], ['75.2.18.233'], 443)\n", '\n']

文件Rules.txt的内容如下:

Rule(F1, HTTPS TCP, ['ip', 'ip'], ['www.google.ca', '8.8.8.8'], 443)

Rule(F2, HTTPS TCP, ['ip', 'ip'], ['ip'], 443)

我想把这些值传入自定义的Rule类:

class Rule:
    def __init__(self, flowNumber, protocol, port, fromIP=[], toIP=[]):
        self.flowNumber = flowNumber
        self.protocol = protocol
        self.port = port
        self.fromIP = fromIP
        self.toIP = toIP

    def __repr__(self):
        return f'\nRule({self.flowNumber}, {self.protocol}, {self.fromIP}, {self.toIP}, {self.port})'

newRule = Rule(currentFlowNum, currentProtocol, currentPort, currentFromIP, currentToIP)

最终要得到类似这样的变量赋值效果:

currentFlowNum = F1, currentProtocol = 'HTTPS TCP' , currentPort = 443, currentFromIP = ['ip', 'ip'], currentToIP = ['www.google.ca', '8.8.8.8']

我试过这段代码拆分规则:

for rule in rulesList:
        if rule !='\n':
            tmp = rule.split(',')
            print(tmp)

但得到的结果是把方括号里的逗号也拆分了:

['Rule(F1', ' HTTPS TCP', " ['ip'", " 'ip']", " ['www.google.ca'", " '8.8.8.8']", ' 443)\n']
['Rule(F2', ' HTTPS TCP', " ['ip'", " 'ip']", " ['ip']", ' 443)\n']

有没有办法不拆分方括号[]内的逗号,得到这样的拆分结果?

['Rule(F1', ' HTTPS TCP', " ['ip','ip']", " ['www.google.ca', '8.8.8.8']", ' 443)\n']
['Rule(F2', ' HTTPS TCP', " ['ip','ip']", " ['ip']", ' 443)\n']
解决方案

方法1:正则表达式精准分割

用正则匹配不在方括号内的逗号作为分隔符,就能保留方括号内的完整内容:

import re

rulesList = ['\n', "Rule(F1, HTTPS TCP, ['ip', 'ip'], ['www.google.ca', '8.8.8.8'], 443)\n", '\n', "Rule(F2, HTTPS TCP, ['ip', 'ip'], ['75.2.18.233'], 443)\n", '\n']

for rule in rulesList:
    if rule.strip() == '':
        continue
    # 匹配不在[]范围内的逗号
    parts = re.split(r',(?![^\[]*\])', rule)
    # 清理每个部分的空格和换行符
    cleaned_parts = [part.strip().rstrip('\n') for part in parts]
    print(cleaned_parts)

运行输出:

['Rule(F1', 'HTTPS TCP', "['ip', 'ip']", "['www.google.ca', '8.8.8.8']", '443)']
['Rule(F2', 'HTTPS TCP', "['ip', 'ip']", "['75.2.18.233']", '443)']

方法2:直接解析为Python对象(更推荐)

你的规则字符串本身符合Python语法,用ast.literal_eval直接解析成元组,比手动拆分更可靠:

import ast

rulesList = ['\n', "Rule(F1, HTTPS TCP, ['ip', 'ip'], ['www.google.ca', '8.8.8.8'], 443)\n", '\n', "Rule(F2, HTTPS TCP, ['ip', 'ip'], ['75.2.18.233'], 443)\n", '\n']

rule_objects = []
for rule in rulesList:
    line = rule.strip()
    if not line:
        continue
    # 把Rule(...)替换成元组格式,方便解析
    tuple_str = line.replace('Rule(', '(').replace(')', ',)')
    # 解析为元组
    parsed = ast.literal_eval(tuple_str)
    # 按Rule类的参数顺序提取值
    flow_num, protocol, from_ip, to_ip, port = parsed
    # 创建Rule实例
    new_rule = Rule(flow_num, protocol, port, from_ip, to_ip)
    rule_objects.append(new_rule)

# 打印结果
for r in rule_objects:
    print(r)

运行输出:

Rule(F1, HTTPS TCP, ['ip', 'ip'], ['www.google.ca', '8.8.8.8'], 443)
Rule(F2, HTTPS TCP, ['ip', 'ip'], ['75.2.18.233'], 443)

补充:优化文件读取代码

可以简化读取逻辑,同时自动过滤空行:

def readFile():
    rulesList = []
    with open('Rules.txt', 'r') as file:
        for line in file:
            stripped_line = line.strip()
            if stripped_line:
                rulesList.append(stripped_line)
    return rulesList

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:15:41