Python读取并分离字符串和d

2024-09-28 01:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样格式的输入文件

{A}
4.240000     1.593631     1.593631
4.240000    -1.593631     1.593631
4.240000    -1.593631    -1.593631
4.240000     1.593631    -1.593631
{B}
-4.240000    -1.593631    -1.593631
-4.240000     1.593631    -1.593631
{C}
...

我想读{A},保存下面的数组,使用数组,然后移到{B}执行同样的操作,。。。你知道吗

我有这样的东西

import sys

#Read file
inFile = sys.argv[1]

with open(inFile) as vfile:
line = vfile.readline()

while line:

    if line.find("{") == 0:
        A = line.split('\n')
    else:
        line.split()
        array = []
        line = [int(i) in line]
        array.append(line)
    print(A, array)

Tags: 文件importread格式withsysline数组
1条回答
网友
1楼 · 发布于 2024-09-28 01:28:41
import re

data = {}
key = None
for line in file:
    line = line.strip()
    if line.endswith('}'):
        key = line[1:-1]
        data[key] = []
    elif line and key is not None:
        # if the number of spaces can be different
        values = re.split('\s+', line)
        data[key].extend(map(float, values))

你会得到如下数据:

{'A': [4.24, 1.593631, 1.593631, ...], 'B': [-4.24, -1.593631, -1.59, ...] ...}

相关问题 更多 >

    热门问题