在 python 中使用多个定界符进行解析

parsing using multiple delimiters in python

我有一个数据文件,其中的数据以逗号、制表符和换行分隔符存储,如下所示

[32135,    311351,    88686
123152,    3153131,    131513
....]

我想从中提取一个nx3数组 我该怎么做?

曾尝试在分割线中使用拆分,但它只是部分解析了文件

import numpy as np
filename="Elem_Output.inp"
f = open(filename,"r")
pmax=f.read()
p1=pmax.split()

我希望提取一个数组,每行一行,数组列中每列的数字

pmax=f.read()后,你可能要这样写:

#Replace tab and newline as comma separater
pmax = pmax.replace("\n",",").replace("\t", ",")

#Replace repeated delimiter by a single instance
pmax = pmax.replace(",,,",",").replace(",,",",")

不用说,使用正则表达式(重新导入)可以更好地编码。

其次,如果您的文件以方括号开头和结尾,您可能还需要添加:

pmax = pmax.replace("[","").replace("]","")

现在,如果您希望此输出为数组而不是列表,请尝试以下操作:

from array import array
array_pmax = array("B", pmax)

array() 函数中的第一个参数表示类型代码。要了解更多,只需使用 help(array)

希望对您有所帮助!!