用python抓取数据及画图(用python处理文字数据)

来源:互联网 发布:理正深基坑支护软件 编辑:程序博客网 时间:2024/06/18 18:12

要求

要从输入文件data.txt中找到含有energy的那一行,然后读出后面的数字,画图。

输入的源文件 data.txt

...

    energy1:   27.35

    energy2:   27.37

    energy3:   35.68

    energy4:   45.12

...

分析

要用python实现以下功能:

1 打开文件(cite [1])

2 把文件内容存入字符变量中以便处理(cite [1])

3 处理字符变量:

       找到我们想要的字符,如“27.35”(cite [2])

       把字符转换成数字 (cite[2])

4 画图

      根据给出的横坐标list,纵坐标list作图,并修改x,y轴名称,图的title(cite [3][4])

源代码 

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import string 
import numpy as np 
import matplotlib.pyplot as plt 

filename="data.txt" 
f=file(filename)       #打开文件 
data=[]                     #list类型变量,准备存放energy数列 
while True:              #一行一行,把整个文件读完 
    line=f.readline()       #读入文件的一行,每读一次,转入下一行 
    if len(line)==0:          #len=0表示EOF(文件结束) 
        break 
    if string.find(line,"energy")!=-1:          #如果这一行有energy字样 
        data.append(string.atof(string.split(line)[1]))      #split把一整行分成一个list,取第二个元素,然后用atof把字符转浮点数,利用append添入data这个list的末端 

fig=plt.figure()                     #新建figure容器的一个实例fig 
ax=fig.add_subplot(111)      #在figure容器中新建axis容器的一个实例ax 
ax.set_xlabel("Index")          #调用对象ax的method:set_xlabel,设置该容器的xlabel 
ax.set_ylabel(r'$E_{total}$')  #使用python内置的latex编译器 
ax.set_title("Finding Best coefficient") 
ax.plot(range(len(data)),data)          #在axis容器中画图 
plt.show()                              #show,生成一个图形化窗口,把画出来的结果展示出来。如果用ssh登录,需要加上-X属性 
f.close()                                 #关闭文件

Reference

[1]《简明python教程》文件调用

http://linux.chinaitlab.com/manual/Python_chinese/ch12.html#using

[2]Python v2.7.2 documentation »The Python Standard Library »7. String Services »字符操作可用函数库

http://docs.python.org/library/string.html#deprecated-string-functions

[3]matplotlib的例子

http://matplotlib.sourceforge.net/examples/api/quad_bezier.html#api-example-code-quad-bezier-py

[4]《用python作科学计算》基础篇 ChapterVI matplotlib-绘制精美的图表

快速制图 http://hyry.dip.jp/pydoc/matplotlib_intro.html#matplotlib

容器概念 http://hyry.dip.jp/pydoc/matplotlib_intro.html#artist

转载请注明原始地址:

http://blog.renren.com/blog/bp/Q7i0Dvm1fW

原创粉丝点击