gpt4 book ai didi

python - 在Python中使用多个分隔符进行解析

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:14 24 4
gpt4 key购买 nike

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

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

我想从中提取一个nx3数组我怎样才能做到这一点?

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

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(",,",",")

不用说,使用正则表达式(import re)可以更好地编码。

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

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

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

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

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

希望有帮助!!

关于python - 在Python中使用多个分隔符进行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56959440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com