python - 具有多个分隔符的拆分列表

标签 python python-3.x list

我有一个列表,其中包含 txt 文件中各行的字符串。

import csv
import re
from collections import defaultdict

parameters = ["name", "associated-interface", "type", "subnet", "fqdn", "wildcard-fqdn", "start-ip", "end-ip", "comment"]
address_dict = defaultdict(dict)
address_statements = []

with open("***somepaths**\\file.txt",
          "r") as address:
    in_address = False
    for line in address:
        line = line.strip()
        #print (line)

        if in_address and line != "next":
            if line == "end":
                break
            address_statements.append(line)
        else:
            if line == "config firewall address":
                in_address = True
    #print(address_statements)

    if address_statements:
        for statement in address_statements:

            op, param, *val = statement.split()

            if op == "edit":

                address_id = param
            elif op == "set" and param in parameters:
                address_dict[address_id][param] = ' '.join(val)

# output to the CSV
with open("***somepaths**\\file.csv", "w",
          newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=parameters)
    writer.writeheader()
    for key in address_dict:
        address_dict[key]['name'] = key
        writer.writerow(address_dict[key])

输出应该是这样的:编辑“name test”,但结果是在名称后面发出空格,并且像这样:edit“name

如何将所有内容都包含在双引号中?

最佳答案

您正在使用

op, param, *val = statement.split()

以空格分割 - 一行

edit "CTS SVR"'

会将 '-edit' 放入 op 中,将 '"CTS' 放入 param 中,其余部分将行(以空格分割为列表)转换为 val:['SVR"']

您需要一种方法 Split a string by spaces preserving quoted substrings - 如果您有内部由空格分隔并由引号分隔的参数。

灵感来自this answer csv 模块可以满足您的需求:

t1 = 'edit1 "some text" bla bla'
t2 = 'edit2 "some text"'
t3 = 'edit3 some thing'
import csv

reader = csv.reader([t1,t2,t3], delimiter = " ", skipinitialspace = True)
for row in reader:
    op, param, *remainder = row
    print(op,param,remainder, sep = " --> ")

输出:

edit1 --> some text --> ['bla', 'bla']
edit2 --> some text --> []
edit3 --> some --> ['thing']

您只能将阅读器应用于一行 ( reader = csv.reader([line], delimiter = "") )。

<小时/>

可能是 Split a string by spaces preserving quoted substrings 的重复项- 我之前对这个问题投了接近票,不能再投票给重复的票 - 因此有了详细的答案。

关于python - 具有多个分隔符的拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59289343/

相关文章:

python - 如何在openpyxl图表中显示日期格式

python - 细数汉诺塔的 Action

python - 实现 copy.deepcopy() 克隆函数

python-3.x - 在 python3 中通过套接字发送 .mp4 文件

python - 使用 Python 解析大型 journalctl 文件以匹配关键字的有效方法

python - 在python中对列表进行排序

python - 使用 pandas 或 numpy 填充缺失的时间序列数据

python - 从拟合图像构建数据集的有效方法

python - 无法对我的列表进行排序,因为它是 NoneType?简单的 python

python - 在python中将列表转换为数据框