从python文件提取以及绘图谈其设计思想

OO~ posted @ 2013年3月28日 10:46 in python , 2231 阅读

    我最近对python特别着迷,学会爬虫抓取数据之后,接着尝试将抓取到的文件数据提取,然后绘制出走势图,后面的这个任务的完成,我用了整整一个下午的时间(不睡午觉),但是最后在代码以及变量函数命名方面做的诸多不足,下面给出我前后代码,谈谈python的设计思想

主模块:

#!/usr/bin/python
# coding = utf-8

import sys
import string
import matplotlib.pyplot as plt
import numpy as np
import getNum #获得歌曲排名,因为设计中文编码问题,单独作为一个自定义模块

def getKey(fileName, s, dist):
    f = open(fileName, "r")
    info = f.read()
    f.close()
    start = info.find(s) + dist
    info = info[start:]
    end = info.find(",")
    return info[:end]

def songDraw():
    x = np.arange(1, 8, 1)
    c = ('y', 'b', 'g', 'r', 'c', 'y', 'b', 'g', 'r', 'c')
    fileDay = ("day1.txt", "day2.txt", "day3.txt", "day4.txt", "day5.txt", "day6.txt", "day7.txt")
    for i in range(0, 10, 1):
        num = []
        tmp = str(i * 20 + 1)
        strlen = len(tmp)
        if strlen == 1:#歌曲的位数要考虑,这样每次截取得到的才是正确的
            dist = 2
        elif strlen == 2:
            dist = 3
        else:
            dist = 4
        key = getKey("day1.txt", tmp, dist)
        num.append(i * 20 + 1)
        for j in range(1, 7, 1):
            num.append(int(getNum.getY(fileDay[j], key)))
        print num
        if i < 5:
            plt.plot(x, num, color=c[i], label="Monday's rank NO."+tmp)
        else:
            plt.plot(x, num, linestyle='--', color=c[i], label="Monday's rank NO."+tmp)
#        plt.plot(x, num, color=c[i], label=u(key))
    plt.legend(loc='upper right')
    plt.title("The song's seven-day rank")
    plt.xlabel("days")
    plt.ylabel("rank")
    plt.grid(True)
    plt.show()

if __name__ == '__main__':
    songDraw()

主模块使用到的自定义模块:

#!/usr/bin/python
# -*- coding:gbk -*-

import string

def getY(fileName, key):
    f = open(fileName, "r")
    info = f.read()
    f.close()
#print s
    end = info.find(key) - 1
    if end == -2:
        return 0
    else:
	info = info[:end]
	info = info[::-1]#将字符串反转,从最后面取值
	end = info.find(",")
	info = info[:end]
#print tmp
        return info[::-1]

接下来的是修改之后的:

#!/usr/bin/python
# coding = utf-8

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

def getSongName(file_name, rank):
    info = open(file_name, "r").read()
    start = info.find(rank)
    return info[start:].split(',')[1]

def getSongRank(file_name, songName):
    info = open(file_name, 'r').read()
    end = info.find(songName)
    if end == -1:
        return 201
    else:
        return int(info[:end].split(',')[-2])#使用split之后,函数反转不需要了,中文字符的查找问题也不存在了

def songDraw():
    x = np.arange(1, 8)
    c = ('y', 'b', 'g', 'r', 'c', 'y', 'b', 'g', 'r', 'c')
    fileDay = ("day1.txt", "day2.txt", "day3.txt", "day4.txt", "day5.txt", "day6.txt", "day7.txt")
    for i in range(10):
        songName = getSongName("day1.txt", str(i * 20 + 1))
        num = [getSongRank(fileDay[j], songName) for j in range(7)]#简化的一个亮点
        print num
        if i < 5:
            plt.plot(x, num, color=c[i])
        else:
            plt.plot(x, num, linestyle='--', color=c[i])
    plt.title("The song's seven-day rank")
    plt.xlabel("days")
    plt.ylabel("rank")
    plt.grid(True)
    plt.show()

if __name__ == '__main__':
    songDraw()

    可以看到,两者之间有非常明显的区别。前后代码量以及松散程度得到了很好的对比。作为一个菜鸟,感觉对python最重要的三大数据结构list,string以及字典使用的还是不到位,不过通过这个训练过程,我至少学会了如何去调试python。同时,在命名规范上,我要做到更加简洁明了。

    其实之前写的C代码多了,所以总感觉在for循环里计算的东西能放在外面就放在外面,经高人提点,python最初的设计理念就不是这样的。python作为一种解释执行的编程语言,其最大的优点之一是它使你能够专注于解决问题而不是去搞明白语言本身。作为每一个python代码的书写者,都要牢记简洁是python的一大美,简洁才能做到易读易看,简洁才能让自己的代码更加优美,不会太慵懒!在网上搜了下——python之禅:

  1. 优美胜于丑陋(Python 以编写优美的代码为目标)
  2. 明了胜于晦涩(优美的代码应当是明了的,命名规范,风格相似)
  3. 简洁胜于复杂(优美的代码应当是简洁的,不要有复杂的内部实现)
  4. 复杂胜于凌乱(如果复杂不可避免,那代码间也不能有难懂的关系,要保持接口简洁)
  5. 扁平胜于嵌套(优美的代码应当是扁平的,不能有太多的嵌套)
  6. 间隔胜于紧凑(优美的代码有适当的间隔,不要奢望一行代码解决问题)
  7. 可读性很重要(优美的代码是可读的)

    通过这次的经历,感触还是蛮多的,在代码的技巧以及书写方面也深深觉察到自己的不足,前面的一段路还是很长啊!不过我会加油的,每天进步一点就够了!

Avatar_small
OO~ 说:
2013年3月28日 10:53

感觉有点像记流水帐啊!没办法了,greenhand的境界就只能这样了!

多行相似代码可以通过函数来简洁代码,list的操作,string的操作,中文字符编码等等问题这次都涉及了,我也收益很多!最重要的一点就是不确定,不太理解的地方可以写多个小例子来测试!

PS:小问题——matplotlib中文显示问题不太会弄!

Avatar_small
依云 说:
2013年3月28日 20:50

c = ('y', 'b', 'g', 'r', 'c', 'y', 'b', 'g', 'r', 'c') 为什么不定义成字符串?
为什么不用代码高亮插件?

Avatar_small
OO~ 说:
2013年3月29日 10:48

我觉得元组在这儿也比较符合啊!如果定义成字符串也是可以的。

后面的代码高亮插件,没怎么用过!我去查查看!本人也这代码这样搞这很丑,但是不知道你们都是用的什么,这下知道了,多谢提醒啦~yes

Avatar_small
依云 说:
2013年3月29日 10:55

@OO~: 字符串比较好写 :-)

Avatar_small
OO~ 说:
2013年3月29日 11:03

恩恩,每个人在选择方面有不同的爱好把,嘿嘿!
PS:炯炯的,原来那个高亮的,是我没设置!多谢提醒,我还一直纳闷怎么回事呢!

Avatar_small
안전놀이터 说:
2023年11月26日 18:52

Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers 

Avatar_small
토토먹튀 说:
2023年11月26日 18:53

I’ve read some good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website.

Avatar_small
라이브스코어특징 说:
2023年11月26日 18:54

I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post

Avatar_small
안전놀이터추천 说:
2023年11月26日 18:55

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

Avatar_small
사다리사이트주소 说:
2023年11月26日 18:56

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has the same topic with your article. Thanks, great share 

Avatar_small
먹튀신고 说:
2023年11月26日 18:57

Awesome Website. Keep up the good work.

Avatar_small
밀라노도메인 说:
2023年11月26日 18:58

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has the same topic with your article. Thanks, great share 

Avatar_small
토토사이트 说:
2023年11月26日 19:08

Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that 

Avatar_small
메이저사이트 说:
2023年11月26日 19:11

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has the same topic with your article. Thanks, great share 

Avatar_small
베팅의민족도메인 说:
2023年11月26日 19:11

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

Avatar_small
토토마켓 도메인 说:
2023年11月26日 19:11

That is the excellent mindset, nonetheless is just not help to make every sence whatsoever preaching about that mather. Virtually any method many thanks in addition to i had endeavor to promote your own article in to delicius nevertheless it is apparently a dilemma using your information sites can you please recheck the idea. thanks once more

Avatar_small
사설토토 说:
2023年11月26日 19:17

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.

Avatar_small
오즈포탈 보는법 说:
2023年11月26日 19:20

Thank you so much as you have been willing to share information as ABC.

Avatar_small
베트맨토토PC버전 说:
2023年11月26日 19:22

This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free

Avatar_small
사설토토 说:
2023年11月26日 19:31

This is actually the kind of information I have been trying to find. Thank you for writing this information

Avatar_small
K카지노가입 说:
2023年11月26日 19:34

The worst part of it was that the software only worked intermittently and the data was not accurate. You obviously canot confront anyone about what you have discovered if the information is not right. Writing with style and getting good compliments on the article is quite hard, to be honest.But you’ve done it so calmly and with so cool feeling and you’ve nailed the job. This article is possessed with style and I am giving good compliment. Best! I am a new user of this site so here i saw multiple articles and posts posted by this site,I curious more interest in some of them hope you will give more information on this topics in your next articles.

Avatar_small
먹튀검증커뮤니티 说:
2023年11月26日 19:38

Thanks for every other informative site. The place else may just I get that kind of information written in such an ideal means? I have a venture that I’m just now operating on, and I have been on the look out for such information 

Avatar_small
안전놀이터 说:
2023年11月26日 19:47

On that website page, you'll see your description, why not read through this 

Avatar_small
샌즈카지노회원가입 说:
2023年11月26日 19:49

It is an excellent blog, I have ever seen. I found all the material on this blog utmost unique and well written. And, I have decided to visit it again and again

Avatar_small
엠카지노 说:
2023年11月26日 19:52

The PCSO Lotto Result today and yesterday this October 2023 is here! Refresh page for official winning numbers - 6/58, 6/55, 6/49, 6/45, 6/42, Swertres 

Avatar_small
파워볼게임 说:
2023年11月26日 19:56

On that website page, you'll see your description, why not read through this 

Avatar_small
토토사이트추천 说:
2023年11月26日 19:58

I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit

Avatar_small
메이저사이트가입코드 说:
2023年11月26日 20:01

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post

Avatar_small
먹튀사이트 说:
2023年11月26日 20:08

On that website page, you'll see your description, why not read through this 

Avatar_small
먹튀검증 说:
2023年11月26日 20:09

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

Avatar_small
토토사이트 说:
2023年11月26日 20:15

That appears to be excellent however i am still not too sure that I like it. At any rate will look far more into it and decide personally

Avatar_small
라이브바카라 说:
2023年11月26日 20:20

Awesome Website. Keep up the good work.

Avatar_small
우리카지노 说:
2023年11月26日 20:23

I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work

Avatar_small
토토어택가입 说:
2023年11月26日 20:27

Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers 

Avatar_small
먹튀사이트 说:
2023年11月26日 20:37

I really appreciate this post. I’ve been looking everywhere for this! Thank goodness I found it on Bing. You have made my day! Thanks again!

Avatar_small
가상스포츠분석법 说:
2023年11月26日 20:37

Really a great addition. I have read this marvelous post. Thanks for sharing information about it. I really like that 

Avatar_small
안전놀이터코드 说:
2023年11月26日 20:39

I think this is a really good article. You make this information interesting and engaging. You give readers a lot to think about and I appreciate that kind of writing

Avatar_small
꽁나라주소 说:
2023年11月26日 20:47

I think that thanks for the valuabe information and insights you have so provided here. 

Avatar_small
메이저토토사이트 说:
2023年11月26日 20:56

I’m happy I located this blog! From time to time, students want to cognitive the keys of productive literary essays composing. Your first-class knowledge about this good post can become a proper basis for such people. nice one 

Avatar_small
홀덤사이트추천 说:
2023年11月26日 21:06

On that website page, you'll see your description, why not read through this 

Avatar_small
먹튀검증 说:
2024年1月15日 16:44

I’m glad to locate this say very beneficial for me, because it consists of lot of are seeking for. I constantly choose to admission the man or woman content and this case i discovered in you proclaim. thank you for sharing.

Avatar_small
소액결제현금화 说:
2024年1月15日 21:46

I definitely need to challenge myself to be quiet more. I have forte a lot better but there is surely room for improvement! I feel like an old lady shaking my cane at a young whippersnapper when I say this, but what I wouldn’t give to have people in my real, every day, non virtual life who make it necessary not to spend all my time plugged in.

Avatar_small
스포츠중계 说:
2024年1月15日 22:18

this is really good website, coolest I have ever visit thank you so much, i will follow and stay tuned much appriciated

Avatar_small
카지노사이트 说:
2024年1月15日 22:36

Excellent blog here! This is really fascinating informatic article. Thanks for sharing your thoughts. I truly appreciate individuals like you!

Avatar_small
바카라사이트 说:
2024年1月16日 14:29

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice

Avatar_small
머니맨 说:
2024年1月16日 14:55

It is great, yet take a gander at the data at this address.

Avatar_small
카지노사이트추천 说:
2024年1月16日 15:12

I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post

Avatar_small
industrial outdoor s 说:
2024年1月16日 15:29

I simply want to tell you that I am new to weblog and definitely liked this blog site. Very likely I’m going to bookmark your blog . You absolutely have wonderful stories. Cheers for sharing with us your blog.

Avatar_small
먹튀검증 说:
2024年1月16日 15:46

You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming

Avatar_small
카지노 올인토토 说:
2024年1月16日 16:05

I am happy to find this post very useful for me, as it contains lot of information. I always prefer to read the quality content and this thing I found in you post. Thanks for sharing

Avatar_small
카지노뱅크 说:
2024年1月16日 16:47

I thought I would leave my first comment. I don’t know what to say except that I have.

Avatar_small
카지노 커뮤니티 说:
2024年1月18日 14:21

I feel a lot more people need to read this, very good info!

Avatar_small
안전놀이터 说:
2024年1月22日 16:31

온라인 카지노 커뮤니티 온카허브 입니다. 온카허브는 카지노 먹튀 사이트들과 안전한 카지노 사이트 정보를 공유하고 있습니다. 카지노 먹튀검증 전문팀을 자체적으로 운영함으로써 철저한 검증을 진행하고 있습니다.

Avatar_small
메이저사이트 说:
2024年1月22日 16:33

온라인 카지노 커뮤니티 온카허브 입니다. 온카허브는 카지노 먹튀 사이트들과 안전한 카지노 사이트 정보를 공유하고 있습니다. 카지노 먹튀검증 전문팀을 자체적으로 운영함으로써 철저한 검증을 진행하고 있습니다.
https://oncahub24.com/

Avatar_small
바카라 说:
2024年1月24日 11:35

바카라 바카라사이트 우리카지노 카지노는 바카라, 블랙잭, 룰렛 및 슬롯 등 다양한 게임을 즐기실 수 있는 공간입니다. 게임에서 승리하면 큰 환호와 함께 많은 당첨금을 받을 수 있고, 패배하면 아쉬움과 실망을 느끼게 됩니다.

Avatar_small
하노이 밤문화 说:
2024年1月24日 12:14

하노이 꼭 가봐야 할 베스트 업소 추천 안내 및 예약, 하노이 밤문화 에 대해서 정리해 드립니다. 하노이 가라오케, 하노이 마사지, 하노이 풍선바, 하노이 밤문화를 제대로 즐기시기 바랍니다. 하노이 밤문화 베스트 업소 요약 베스트 업소 추천 및 정리.

Avatar_small
먹튀검증 说:
2024年1月25日 14:55

No.1 먹튀검증 사이트, 먹튀사이트, 검증사이트, 토토사이트, 안전사이트, 메이저사이트, 안전놀이터 정보를 제공하고 있습니다. 먹튀해방으로 여러분들의 자산을 지켜 드리겠습니다. 먹튀검증 전문 커뮤니티 먹튀클린만 믿으세요!!

Avatar_small
베트남 밤문화 说:
2024年1月25日 16:15

베트남 남성전용 커뮤니티❣️ 베트남 하이에나 에서 베트남 밤문화를 추천하여 드립니다. 베트남 가라오케, 베트남 VIP마사지, 베트남 이발관, 베트남 황제투어 남자라면 꼭 한번은 경험 해 봐야할 화끈한 밤문화로 모시겠습니다. 

Avatar_small
블록체인개발 说:
2024年4月23日 18:10

블록체인개발 코인지갑개발 IT컨설팅 메스브레인팀이 항상 당신을 도울 준비가 되어 있습니다. 우리는 마음으로 가치를 창조한다는 철학을 바탕으로 일하며, 들인 노력과 시간에 부흥하는 가치만을 받습니다. 고객이 만족하지 않으면 기꺼이 환불해 드립니다.
https://xn--539awa204jj6kpxc0yl.kr/

Avatar_small
Cryto exchange 说:
2024年6月03日 12:14

The tech-original mission is to help you better understand technology, and make better decisions in the fields of IT, Tech, and Crypto.
https://www.tech-original.com/

Avatar_small
Cryto exchange 说:
2024年6月07日 17:54

The tech-original mission is to help you better understand technology, and make better decisions in the fields of IT, Tech, and Crypto.
https://www.tech-original.com/


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter