来自fi的矢量数据

2024-05-14 21:28:27 发布

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

我刚开始学习Python。我有一些fortran和一些Matlab的技能,但我决不是一个编码器。我需要后处理一些输出文件。你知道吗

我不知道如何将每个值读入相应的变量。数据如下所示:

h5097600N1 2348.13 2348.35 -0.2219 20.0 -4.438
h5443200N1 2348.12 2348.36 -0.2326 20.0 -4.651
h8467200N2 2348.11 2348.39 -0.2813 20.0 -5.627 ...

在我有限的Matlab表示法中,我想指定以下形式为tN1(I,j)的变量如下:

tN1(1,1)=5097600; tN1(1,2)=5443200; tN2(1,3)=8467200; #time between 'h' and 'N#'
hmN1(1,1)=2348.13; hmN1(1,2)=2348.12; hmN2(1,3)=2348.11; #value in 2nd column
hsN1(1,1)=2348.35; hsN1(1,2)=2348.36; hsN2(1,3)=2348.39; #value in 3rd column

我将有大约30套,或tN1(1:30,1:j);hmN1(1:30,1:j);hsN1(1:30,1:j)

我知道这看起来不像,但我已经想了两天了。我正试图自己学习这一点,似乎我对python的理解中缺少了一些基本的东西。你知道吗


Tags: 文件数据invalue技能column编码器后处理
2条回答

我写了一个简单的脚本,你要怎么做就怎么做。它创建了三个字典,t, hmhs。这些键将作为N值。你知道吗

import csv
import re


path = 'vector_data.txt'

# Using the <with func as obj> syntax handles the closing of the file for you.
with open(path) as in_file:
    # Use the csv package to read csv files
    csv_reader = csv.reader(in_file, delimiter=' ')
    # Create empty dictionaries to store the values
    t = dict()
    hm = dict()
    hs = dict()
    # Iterate over all rows
    for row in csv_reader:
        # Get the <n> and <t_i>  values by using regular expressions, only
        # save the integer part (hence [1:] and [1:-1])
        n = int(re.findall('N[0-9]+', row[0])[0][1:])
        t_i = int(re.findall('h.+N', row[0])[0][1:-1])

        # Cast the other values to float
        hm_i = float(row[1])
        hs_i = float(row[2])

        # Try to append the values to an existing list in the dictionaries.
        # If that fails, new lists is added to the dictionaries.
        try:
            t[n].append(t_i)
            hm[n].append(hm_i)
            hs[n].append(hs_i)
        except KeyError:
            t[n] = [t_i]
            hm[n] = [hm_i]
            hs[n] = [hs_i]

输出:

>> t
{1: [5097600, 5443200], 2: [8467200]}
>> hm
{1: [2348.13, 2348.12], 2: [2348.11]}
>> hn
{1: [2348.35, 2348.36], 2: [2348.39]}

(记住Python使用零索引)

谢谢你的评论。建议的阅读材料导致了其他有帮助的事情。下面是我想到的:

if len(line) >= 45:
    if line[0:45] == " FIT OF SIMULATED EQUIVALENTS TO OBSERVATIONS": #! indicates data to follow, after 4 lines of junk text
         for i in range (0,4):
             junk = file.readline()
         for i in range (0,int(nobs)):
             line = file.readline()
             sline = line.split()
             obsname.append(sline[0])
             hm.append(sline[1])
             hs.append(sline[2])

相关问题 更多 >

    热门问题