【发布时间】:2018-04-26 03:57:57
【问题描述】:
我想在 python 中解析一个看起来像这样的平面文件;
Element ID Element Type Result Jacobian Sign
============== ================= ========= =====================
1 Parabolic Warning 1.000000
Hexahedron
2 Parabolic Warning 1.000000
Hexahedron
3 Parabolic Warning 1.000000
Hexahedron
4 Parabolic Warning 1.000000
我尝试使用this answer中使用的机制如下;
import pandas as pd
def parse_file(file):
col_spec = [(0, 15), (16, 33), (34, 43), (44, 65)]
return pd.read_fwf(file, colspecs=col_spec)
但它会读取第一行的一条记录和除了单词“Hexahedron”作为元素类型之外的另一行。
>>> data = parse_file("example.txt")
>>> data.head()
Element ID Element Type Result Jacobian Sign
0 NaN NaN NaN NaN
1 ============== ================ ======== ====================
2 1 Parabolic Warning 1.000000
3 NaN Hexahedron NaN NaN <= Extra record
4 2 Parabolic Warning 1.000000
从行中可以看出,前两行被捕获为 2 条记录(记录 2 和 3)。我希望解析器将前两行捕获为一条记录,以便将短语“抛物线六面体”捕获为元素类型。我该怎么做?
【问题讨论】:
-
展示你的尝试。解释期望的行为以及它与预期的不同之处。