文本文件: 我有一个包含超过 87,000 个数据点的文本文件。文本文件的格式如下:
- X 坐标 ----- Y 坐标 ---------- 参数 1 ------ 参数 2--------
- 2.744596610E-02 1.247197202E+00 7.121462841E-03 2.467938066E-05
- 2.732558411E-02 1.242196291E+00 1.365028508E-02 6.262368697E-05
- 2.713870635E-02 1.227254209E+00 1.958976965E-03-3.179617352E-06
由于前导 -(减号) 符号,两个以粗体突出显示的数字之间没有空格,因此生成的 csv/pandas 数据框会产生一些结果像下面这样。
输出:
| X Coordinate | Y Coordinate | Parameter 1 | Parameter 2 |
| -------------- | -------------- | --------------- | ------------ |
| 2.744596610E-02 | 1.247197202E+00 | 7.121462841E-03 | 2.467938066E-05 |
| 2.732558411E-02 | 1.242196291E+00 | 1.365028508E-02 | 6.262368697E-05 |
| 2.713870635E-02 | 1.227254209E+00 | 1.958976965E-03-3.179617352E-06| |
必填:
| X Coordinate | Y Coordinate | Parameter 1 | Parameter 2 |
| -------------- | -------------- | --------------- | ------------ |
| 2.744596610E-02 | 1.247197202E+00 | 7.121462841E-03 | 2.467938066E-05 |
| 2.732558411E-02 | 1.242196291E+00 | 1.365028508E-02 | 6.262368697E-05 |
| 2.713870635E-02 | 1.227254209E+00 | 1.958976965E-03 |-3.179617352E-06 |
我对 python/pandas 很熟悉,因此任何编程技术都会有很大帮助。
最佳答案
import re
DATAPOINT = re.compile(r'-?\d{1}\.\d{9}E[+-]\d{2}')
data = []
with open("data.txt") as fp:
next(fp) # Ignore header (1st line)
for l in fp.readlines():
data.append(DATAPOINT.findall(l))
df = pd.DataFrame(data, columns=['X Coordinate', 'Y Coordinate', 'Parameter 1', 'Parameter 2'])
>>> df
X Coordinate Y Coordinate Parameter 1 Parameter 2
0 2.744596610E-02 1.247197202E+00 7.121462841E-03 2.467938066E-05
1 2.732558411E-02 1.242196291E+00 1.365028508E-02 6.262368697E-05
2 2.713870635E-02 1.227254209E+00 1.958976965E-03 -3.179617352E-06
关于python - 读取带有负数的文本文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68058307/