用python解决生活中的难题

我曾在以前的文章中提到过学习的方法,“即对于工程类的科目,应以实践为主导的进行学习”。同时,上个学期的时候也跟朋友各种吐槽用c语言时的各种不爽,其更适合作为一种教学语言,而python不但语法简单,功能也异常强大,真是居家旅行打家劫舍抢劫强奸之必备必须必不可少之利器也!

我几乎没有学过python语言,只是大致看了看语法,平常碰到复杂事情不免遇到要编程解决的时候,懒得打开IDE,边直接拿python练手了。

第一个碰到的问题是,论文的参考目录要求改成按作者姓氏排序。原始的数据如下:

[1] A. Ude and R. Dillmann, “Vision-based robot path planning,” Adv. Robot Kinematics Comput. Geometry, pp. 505–512, 1994.
[2] N. Dimitrova, H.-J. Zhang, I. Sezan, T. S. Huang, and A. Zakhor, “Applications of video-content analysis and retrieval,” IEEE Multimedia, vol. 9, no. 3, pp. 42–55, Mar. 2002.
[3] D. Tao, X. Tang, X. Li, and X. Wu, “Asymmetric bagging and random subspace for support vector machines-based relevance feedback in image retrieval,” IEEE Trans. Pattern Anal. Mach. Intell., vol. 28, no. 7, pp. 1088–1099, Jul. 2006.
[4] B. Bose and E. Grimson, “Learning to use scene context for object classification in surveillance,” presented at the IEEE Int. Workshop on Visual Surveillance and Performance Evaluation of Tracking and Surveillance, 2003.
[5] G. Pass, R. Zabih, and J. Miller, “Comparing images using color coherence vectors,” in Proc. ACM Int. Conf. Multimedia, 1996, pp. 65–73.
[6] B. Manjunath and W. Y. Ma, “Texture features for browsing and retrieval of image data,” IEEE Trans. Pattern Anal. Mach. Intell., vol. 18, no. 8, pp. 837–842, Aug. 1996.
[7] A. K. Jain and A. Vailaya, “Image retrieval using color and shape,” Pattern Recognit., vol. 29, no. 8, pp. 1233–1244, 1996.  

其中Ude,Dimitrova和Tao等便是姓氏,所以我们应该按照这些词来进行排序。 代码如下:

#! /usr/bin/env python
#coding=utf-8
import re
str="""
...
"""
list=re.split('\[.*\]',str)
list.pop(0)
plist=sorted(list,key=lambda x:x[3:])
for pp in plist:
    print pp.decode('utf-8').encode('cp936')

我这个参考文献有50多条,如果人眼手动调整顺序,估计得一下午,到时候估计钛合金狗眼也得瞎了。

第二个问题是我当助教时碰到的,当时所有的学生的实验报告都要提交到ftp里,而我助教的工作就是要一个一个检查他们的实验报告。整个系有100多人,每个人的实验报告都看,疯了吧,不过检查还是要检查的,由于每个实验报告的提交都有时间限制,不如我先写个程序来统计下大家的提交时间吧。

from ftplib import FTP
remotefiles=[]
localdir='***'
ftp=FTP('***')
ftp.login('***')
ftp.dir(localdir,remotefiles.append)
del remotefiles[:3]
for remotefile in remotefiles:
    parsed=remotefile.split(None,8)
    print parsed[5],parsed[6],parsed[8] 然后想了想,觉得这样有点太不负责任了,于是又写了程序遍历ftp上所有目录来看看  

def fileornot(file):
parsed=file.split(None,8)
print parsed,'\n'
permiss=parsed[0]
print permiss,'\n'
if permiss[0]!='d':
    return 1
else:
    return 0
def displayfiles(dir):
remotefiles=[]
ftp.dir(dir,remotefiles.append)
#print remotefiles
for i in remotefiles:
    parsed=i.split(None,8)
    if len(parsed)<6:
        continue
    if parsed[8] in ('.','..'):
        continue
    file=dir+'/'+parsed[8]
    #print file
    permiss=parsed[0]
    if permiss[0]=='d':
        displayfiles(file)
       # ftp.cwd('..')
    else:
        print file
return 0
displayfiles(localdir)

最后就是经常用到的html分析了,年前的时候下载电视剧,可是网上的电视剧都是一集一集的链接,如

<a href="ed2k://|file|废柴联盟.Community.S01E01.Chi_Eng.HDTVrip.720X396-YYeTs人人影视.rmvb|99234907|75A3A8037A44FC4F889C75C46CCCBA1E|h=2BRSD5L45QKMDXQEYOI3JP2RMDEWK7ED|/" target="_blank">[第01集]</a>
<a href="ed2k://|file|废柴联盟.Community.S01E02.Chi_Eng.HDTVrip.720X396-YYeTs人人影视.rmvb|87461247|9334A1917079DF844F382EBF450F169B|h=NYT2LO4SPHSDNAJEI6244BXCSKWAN3KN|/" target="_blank">[第02集]</a>

使用lxml来做代码如下

# -*- coding: UTF-8 -*-
from lxml import etree
html = u"""
<a href="ed2k://|file|废柴联盟.Community.S01E01.Chi_Eng.HDTVrip.720X396-YYeTs人人影视.rmvb|99234907|75A3A8037A44FC4F889C75C46CCCBA1E|h=2BRSD5L45QKMDXQEYOI3JP
"""
tree = etree.HTML(html)
ret = tree.xpath('//a[starts-with(@href,"ed2k://")]')
for i in ret:
print i.get('href').encode('cp936') 后来学习了BeautifulSoup,发现bs的功能确实非常的强大,于是想用bs来提取团购网站的一些东西,提取团购的内容和价格信息相对比较简单,却在提取图片的时候遇到不少问题,大多都是html格式不统一造成的,比如有的图片地址在这个属性里,而有的在另一个属性里等等。总之我用bs写的时候出现很多问题,后来改用lxml里xpath问题就自然迎刃而解了。

# -*- coding: UTF-8 -*-
from lxml import etree
import urllib
import re;
html=urllib.urlopen('http://bj.meituan.com/').read()
tree = etree.HTML(html)
ret = tree.xpath('//img[@gaevent]')
for i in ret:
    temp1=i.get('data-params')
    if temp1:
        print re.search("http[^\'].*jpg",temp1).group()
    else:
        temp2=i.get('src')
        print re.search("http[^\'].*(jpg|png)",temp2).group().encode('cp936')



comments powered by Disqus