Python将数据读入数组或列表

Python将数据读入数组或列表,python,arrays,numpy,matplotlib,Python,Arrays,Numpy,Matplotlib,我需要从文本文件中读取数据,对其进行操作,并将其全部存储在数组、列表或其他数据结构中,以便将其制表,并使用matplotlib进行打印 我打算有一个输入语句来存储治疗日期和时间。输入文件中的日期和时间将从此日期时间中减去,以给出自治疗以来的时间(分钟或小时) 首先,我正在使用的输入文件的格式如下: !05/04/2014 @1332 Contact Angle (deg) 106.87 Contact Angle Left (deg) 106.90 Contact Angle Ri

我需要从文本文件中读取数据,对其进行操作,并将其全部存储在数组、列表或其他数据结构中,以便将其制表,并使用matplotlib进行打印

我打算有一个输入语句来存储治疗日期和时间。输入文件中的日期和时间将从此日期时间中减去,以给出自治疗以来的时间(分钟或小时)

首先,我正在使用的输入文件的格式如下:

!05/04/2014
@1332
Contact Angle (deg)     106.87
Contact Angle Left (deg)    106.90
Contact Angle Right (deg)   106.85
Wetting Tension (mN/m)      -21.13
Wetting Tension Left (mN/m) -21.16
Wetting Tension Right (mN/m)    -21.11
Base Tilt Angle (deg)       0.64
Base (mm)           1.7001
Base Area (mm2)         2.2702
Height (mm)         1.1174
Sessile Volume (ul)     2.1499
Sessile Surface Area (mm2)  6.3842
Contrast (cts)          255
Sharpness (cts)         186
Black Peak (cts)        0
White Peak (cts)        255
Edge Threshold (cts)        105
Base Left X (mm)        2.435
Base Right X (mm)       4.135
Base Y (mm)         3.801
RMS Fit Error (mm)      2.201E-3

@1333
Contact Angle (deg)     105.42
Contact Angle Left (deg)    106.04
Contact Angle Right (deg)   104.80
Wetting Tension (mN/m)      -19.36
Wetting Tension Left (mN/m) -20.12
Wetting Tension Right (mN/m)    -18.59
Base Tilt Angle (deg)       0.33
Base (mm)           1.6619
Base Area (mm2)         2.1691
Height (mm)         0.9837
Sessile Volume (ul)     1.6893
Sessile Surface Area (mm2)  5.3962
Contrast (cts)          255
Sharpness (cts)         190
Black Peak (cts)        0
White Peak (cts)        255
Edge Threshold (cts)        105
Base Left X (mm)        2.397
Base Right X (mm)       4.040
Base Y (mm)         3.753
RMS Fit Error (mm)      3.546E-3
在文件中,每个新日期都以“!”开头并采用所示格式(dd/mm/yyyy)

表格应包含输入文件中的日期时间、接触角以及治疗后的分钟数

下面的代码从文本文件中提取所需的相关信息并将其写入另一个文件,但我不知道存储信息的最佳方式是什么

with open(infile) as f, open(outfile, 'w') as f2:
    for line in f:
        if line.split():
            if line.split()[0][0] == '!':
                for i in range(1,11):
                    current_date += (line.split()[0][i])
                f2.write(current_date[:2] + ' ' + current_date[3:5] + ' ' + current_date[6:] + '\n')
            current_date = ""
            if line.split()[0][0] == '@':
                for i in range(0,5):
                    measure_time += (line.split()[0][i])
                f2.write(measure_time[1:3] + ":" + measure_time[3:] + '\n')
            if line.split()[0] == "Contact" and line.split()[2] == "(deg)":
                contact_angle = line.split()[-1].strip()
                f2.write("Contact Angle (deg): " + contact_angle + '\n\n')
            measure_time = ""
        else:
            continue
我也一直在玩datetime,有一些代码可以从单个输入计算治疗后的时间,但我需要将其应用于输入文件中的每个日期和时间

from datetime import datetime
import numpy as np

dt = input("Enter treatment date and time in format: dd mm yyyy hh:mm\n")
#dt = '27 03 2014 12:06'

dob = datetime.strptime(dt,'%d %m %Y %H:%M')



b = datetime(2014,3,27,16,22,0)
c = b-dob
print(c.seconds)
print(c.seconds/60)
print(c.seconds//3600)
最后,我想使用matplotlib绘制治疗后接触角与时间的关系图


如果有人能帮我这个忙,我将不胜感激。

以下是如何解析此类文件。所有内容都存储在包含字典的字典中(一直到下面的海龟:)。主键ar ID(@smth)

另一种方法是按日期存储,每一项都是按ID列出的词典。但这对于
collections.defauldict
来说是最容易做到的,这可能会让你有点困惑。因此,下面的解决方案可能不是最好的,但对您来说应该更容易理解

data = {}

date = ID = values = None

for line in datafile:
    if line.lstrip().startswith('!'):
        date = line[1:].strip()
        print date, line
    elif line.lstrip().startswith('@'):
        ID = line[1:].strip()
        data[ID] = {}
        data[ID]['date'] = date
    elif line.strip(): # line not all whitespace
        if not ID: 
            continue # we skip until we get next ID
        try:
            words = line.split()
            value = float(words[-1]) # last word
            unit = words[-2].lstrip('(').rstrip(')')
            item = {'value': value, 'unit': unit}
            key = ' '.join(words[:-2])
            data[ID][key] = item
        except (ValueError) as err:
            print "Could not parse this line:"
            print line
            continue
    else: # if 'empty' line
        ID = None

我鼓励你逐行分析这一点,在中查找方法。如果你真的被困在评论中,有人会给你一个指向更具体页面的链接。GL.

以下是如何解析此类文件。所有内容都存储在包含字典的字典中(一直到下面的海龟:)。主键ar ID(@smth)

另一种方法是按日期存储,每一项都是按ID列出的词典。但这对于
collections.defauldict
来说是最容易做到的,这可能会让你有点困惑。因此,下面的解决方案可能不是最好的,但对您来说应该更容易理解

data = {}

date = ID = values = None

for line in datafile:
    if line.lstrip().startswith('!'):
        date = line[1:].strip()
        print date, line
    elif line.lstrip().startswith('@'):
        ID = line[1:].strip()
        data[ID] = {}
        data[ID]['date'] = date
    elif line.strip(): # line not all whitespace
        if not ID: 
            continue # we skip until we get next ID
        try:
            words = line.split()
            value = float(words[-1]) # last word
            unit = words[-2].lstrip('(').rstrip(')')
            item = {'value': value, 'unit': unit}
            key = ' '.join(words[:-2])
            data[ID][key] = item
        except (ValueError) as err:
            print "Could not parse this line:"
            print line
            continue
    else: # if 'empty' line
        ID = None

我鼓励你逐行分析这一点,在中查找方法。如果你真的被困在评论中,有人会给你一个指向更具体页面的链接。GL.

您显然有记录,因此您的数据将以这样的方式进行最佳组织

示例中的每条记录都以
@
开头(然后我假设是一个度量指标)。每个记录都有一个额外的字段:顶部列出的日期

records = []
record = {}
for line in f:
    kv = line.strip().split('\t')
    if kv[0].startswith('@'):
        record['measurement_date'] = msr_date
        records.append(record)  # store the last record
        record = {}  # make a new empty record
        for n in range(21):
            kv = f.next().strip().split('\t')
            quantity = kv[0].split('(')[0].strip()
            value = float(kv[1])
            record[quantity] = value
    elif kv[0].startswith('!'):
        msr_date = datetime.strptime(kv[0][1:], "%d/%m/%Y")   # append it to the record later
    else: 
        pass  # empty line
records.pop()  # The first record is a dummy record
# the last record has nog been appended yet
record['measurement_date'] = msr_date
records.append(record)
最后,您将得到一个字典列表
记录
。
然后,您可以循环使用这些文件,以更有效的形式存储它们,例如使用

请注意,如果
datetime64
是您所需的格式,您必须进行查找(请查看该格式)

使用最后一个
arr
您可以将所有内容整齐地放置在“列”中,但您可以按名称访问它们


plt.绘图(arr[‘消失时间’],arr[‘接触角’)

但是您必须告诉matplotlib对其独立变量使用timedelta参数,正如。

您显然有记录,因此您的数据将以这样的方式进行最佳组织

示例中的每条记录都以
@
开头(然后我假设是一个度量索引)。每条记录都有一个额外的字段:顶部列出的日期

records = []
record = {}
for line in f:
    kv = line.strip().split('\t')
    if kv[0].startswith('@'):
        record['measurement_date'] = msr_date
        records.append(record)  # store the last record
        record = {}  # make a new empty record
        for n in range(21):
            kv = f.next().strip().split('\t')
            quantity = kv[0].split('(')[0].strip()
            value = float(kv[1])
            record[quantity] = value
    elif kv[0].startswith('!'):
        msr_date = datetime.strptime(kv[0][1:], "%d/%m/%Y")   # append it to the record later
    else: 
        pass  # empty line
records.pop()  # The first record is a dummy record
# the last record has nog been appended yet
record['measurement_date'] = msr_date
records.append(record)
最后,您将得到一个字典列表
记录
。
然后,您可以循环使用这些文件,以更有效的形式存储它们,例如使用

请注意,如果
datetime64
是您所需的格式,您必须进行查找(请查看该格式)

使用最后一个
arr
您可以将所有内容整齐地放置在“列”中,但您可以按名称访问它们


plt.绘图(arr[‘消失时间’],arr[‘接触角’)

但是,您必须告诉matplotlib为其独立变量使用timedelta参数,如。

您没有说明您的问题。您的问题是什么?如果问题不清楚,很抱歉。我可以将相关数据拉入文件,但我希望能够将上述各点(日期时间、接触角度、治疗后的时间)制成表格我不知道该怎么做,也不知道如何将数据存储在Python中进行操作。你的问题中没有什么问题,一般的规则是一次只能解决一个问题。给我一点时间,我给你举个例子,说明如何解析与你类似的数据(但请不要期待完整的解决方案)。有一件事:你确定文件中的数据是用空格分隔的吗?如果有制表符,解析此文件会更容易理解。非常感谢。标签和值之间的空格是用制表符分隔的。你没有陈述你的问题。你有什么问题?如果问题不清楚,很抱歉。我可以回答我会将相关数据写入一个文件,但我希望能够将上述各点(日期时间、接触角、治疗后的时间)制成表格我不知道该怎么做,也不知道如何将数据存储在Python中进行操作。你的问题中没有什么问题,一般的规则是一次只能解决一个问题。给我一点时间,我给你举个例子,说明如何解析与你类似的数据(但请不要期待完整的解决方案)。有一件事:你确定文件中的数据是用空格分隔的吗?如果有制表符,解析此文件会更容易理解。非常感谢。标签和值之间的空格是用制表符分隔的。我还没有尝试过你的解决方案,但我只是为你写这篇文章