【问题标题】:Python read and separate string and dataPython读取并分离字符串和数据
【发布时间】:2018-07-12 11:38:06
【问题描述】:

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

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

【问题讨论】:

  • 你的问题是......?
  • 您需要单独的数组还是只打印行间?
  • 你能发布预期的输出吗?

标签: python


【解决方案1】:
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, ...] ...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 2013-09-18
    • 2015-07-18
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2017-12-07
    相关资源
    最近更新 更多