python 将alphaMELTS输出文件读入numpy数组以进行绘图和分析

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 将alphaMELTS输出文件读入numpy数组以进行绘图和分析相关的知识,希望对你有一定的参考价值。

# Created 2014, Zack Gainsforth
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import numpy as np
#import QuickPlot
import re
from StringIO import StringIO
import glob
import os

def GetalphaMELTSSection(FileName, SectionName):
    # Read the alphaMELTS file that has all the output.
    try:
        with open (FileName, 'r') as myfile:
            data=myfile.read()
    except:
        print 'Failed to open ' + FileName + '.  Skipping.'
        return

    DataLines = StringIO(data)

    reout = re.compile(r'%s.*?(?:\n\n|\Z)' % (SectionName), re.S)
#    reout = re.compile(r'%s.*?%s' % (SectionName, stop), re.S)
    try:
        SectionStr = reout.search(data).group(0)
    except:
        # It is possible that this MELTS computation didn't produce this mineral.  If so, just bail.
        return None
    # Convert it into a numpy array.
    SectionData = np.genfromtxt(StringIO(SectionStr), skip_header=1, skip_footer=0, names=True)
    return SectionData

def ListalphaMELTSSections(FileName):
    # Read the alphaMELTS file that has all the output.
    try:
        with open (FileName, 'r') as myfile:
            data=myfile.read()
    except:
        print 'Failed to open ' + FileName + '.  Skipping.'
        return

    DataLines = StringIO(data)
    SectionNames = list()
    while True:
        try:
            Line = DataLines.readline()
            if Line == '\n':
                s = DataLines.readline()
                snames = s.split()
                SectionNames.append(snames[0])
            if Line == '':
                break
        except:
            break

    return SectionNames

def ListAllMeltsFiles(PathName=os.getcwd()):

    fnames = glob.glob(os.path.join(PathName, '*.txt'))

    for f in fnames:
        _, filename = os.path.split(f)
        print filename + ': ' + str(ListalphaMELTSSections(f))

    # P = GetalphaMELTSSection('Phase_mass_tbl.txt', 'Phase')
    # P = GetalphaMELTSSection('Phase_main_tbl.txt', 'clinopyroxene_1')

    print 'Example code: '
    _, filename = os.path.split(f)
    print 's = GetalphaMELTSSection(\'' + filename + '\', \'' + ListalphaMELTSSections(f)[0] + '\')'
    s = GetalphaMELTSSection(f, ListalphaMELTSSections(f)[0])
    print 'plot(s[\'' + s.dtype.names[0] + '\'], s[\'' + s.dtype.names[1] + '\'])'
    return

#ListAllMeltsFiles(os.getcwd())

以上是关于python 将alphaMELTS输出文件读入numpy数组以进行绘图和分析的主要内容,如果未能解决你的问题,请参考以下文章

Python读入三个整数,输出它们的和与平均值,其中,平均值保留两位小数?

python 循环读取表格每次读入N行

如何将文件读入 Python 中的列表? [复制]

使用DataX将.csv文件的数据读入Mysql数据库

如何把MATLAB中的数据读入到SIMULINK中

Python将整数从csv文件读入列表