【问题标题】:parsing using multiple delimiters in python在python中使用多个分隔符进行解析
【发布时间】:2019-07-09 19:30:33
【问题描述】:

我有一个数据文件,其中数据用逗号和制表符以及换行符分隔,就像这样

[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()

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

【问题讨论】:

  • 您的文本文件是否包含[ 字符?
  • @MarkMeyer 不,它没有

标签: python parsing delimiter


【解决方案1】:

在 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)

希望有帮助!!

【讨论】:

  • tnx 它有效,但它给了我一个列表,我需要一个数组
  • 欢迎。我现在已经更新了处理您的数组要求的答案。这应该会有所帮助:)
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
相关资源
最近更新 更多