Archive for the ‘python’ Category
调用u.nu的api缩短网址
#coding: utf-8
import sys
import urllib2
api_address = 'http://u.nu/unu-api-simple?url='
for org_url in sys.argv[1:]:
request = urllib2.urlopen(api_address + urllib2.quote(org_url))
short_url = request.read()
if short_url.startswith('http'):
print org_url, '–> ', short_url
else:
print 'Error'
使用lxml解析html文件
之前一直搞错了,实际上只需要使用lxml.html模块,读入html文件后,直接调用xpath定位所需要的内容就行了,不再需要etree什么的了。具体看下面的例子:
02
03 from lxml import *
04 import lxml.html as H
05 import urllib2
06
07 def getart(url):
08 f = urllib2.urlopen(url)
09 content = f.read()
10
11 art = []
12 doc = H.document_fromstring(content)
13 p = doc.xpath(‘/html/body/div[2]/div[2]/div/div/ul/li/div[2]/p’)
14 for i in p:
15 tmp = i.text_content()
16 tmp = tmp.encode(‘utf-8′)
17 tmp = tmp.replace(‘\r‘, ‘\n‘)
18 art.append(tmp)
19 return art
20
21 if __name__ == ‘__main__’:
22 urls = ['http://www.douban.com/group/topic/12018319/',
23 'http://www.douban.com/group/topic/12018319/?start=100']
24 outfile = open(‘zheda.txt’, ‘w’)
25 for url in urls:
26 art = getart(url)
27 for item in art:
28 outfile.write(item+‘\n‘)
29 outfile.close()
附:浙大夜惊魂6月26日更新至101章
hotfile: http://hotfile.com/dl/50704792/39ca85e/626101.txt.html
xun6: http://is.gd/d4Ym0

Learning Python – 01
Python中处理变量的方式和其他语言有很大的不同,尽管这些区别看上去没有那么明显。
Spyder: Python的科学计算IDE
Spyder(之前叫Pydee)是一个面向Python科学计算的IDE。跨平台,轻量级,提供了类似Matlab集成环境的功能。对于Windows平台的用户,可以考虑直接安装Python(x,y)这个发行版,集成了众多常用的与科学计算有关的Python包。

基于Python的针对科学家和工程师的软件工程
Software Engineering with Python for Scientist and Engineers是PSF2005年资助的一项计划,项目主页在Software Carpentry,作者是Greg Wilson。该项目由一系列的讲座组成,帮助科技工作者使用Python快捷的任务。目前作者正在完善第4版。更详细的信息查阅项目主页和作者的Blog。
Lectures
- Introduction
- Python Basics
- Python Strings, Lists, and Files
- Python Functions and Modules
- Debugging
- Version Control
- Python Sets and Dictionaries
- Image Processing
- Basic Unix Shell
- More Unix Shell
- Automated Builds
- Computational Complexity
- Python Basic Object-Oriented Programming
- Python Advanced Object-Oriented Programming
- Quality Assurance
- Unit Testing
- Databases
- Regular Expressions
- Binary Data
- XML
- GUI Programming
- Web Client Programming
- How Web Servers Work
- Web Application Programming
- Empirical Software Engineering
- Software Development Lifecycles
- Summary
- License
- Glossary
- Acknowledgments
- Bibliography

Sage Tutorial中文版
Sage Tutorial是一份快速了解Sage的入门文档,花了两周多的时间将其翻译为中文。但是“Some more advanced mathematics”一节没有翻译,因为完全不熟悉这一节所涉及到的内容。
第一次翻译开源软件的技术文档,水平有限,希望各位多提意见,任何方面的都可以。如果没有大的问题,大概一周后会向Sage开发组提交。
源文件使用Sphinx管理,PDF文件是由自动转换而来的LaTeX文件编译的,因此其中很多格式不符合中文的习惯。所以请大家先以HTML文件为准,最后发布前,我会手工调整LaTeX文件后再编译。
Email: amao@ai7.org
相关内容:翻译Sage文档的准备工作
Ubuntu 9.10下unzip的乱码问题
Ubuntu 9.10中unzip升级为6.0,结果原来的-O参数没有了,解压缩Win平台来的带中文文件名的文件时,会有乱码。Google,Baidu无果后,自行使用Python解决。
01 #!/usr/bin/python
02 #coding=utf8
03
04 import zipfile
05 import sys
06
07 if len(sys.argv)<2:
08 print u’punzip zipfilename’
09 else:
10 f=zipfile.ZipFile(sys.argv[1])
11 nlist=f.namelist()
12 for n in nlist:
13 m=unicode(n,’gb2312′).encode(‘utf8′)
14 file(m,’wb’).write(f.read(n))
15 f.close()
翻译Sage文档的准备工作
打算翻译一下Sage的文档。Sage的文档完全是用reStructuredTEXT写成的,由Sphinx管理,对应的翻译就行了,但是为了与原文档保持相同的风格,还是折腾了好久。这里记录一下。
环境是:Ubuntu+Sage 4.2.1+CTeXLive 2008。以翻译Sage Tutorial为例,需要做以下准备工作。(下面用$SAGE代替sage的主目录)
- 转到$SAGE/devel/sage-main/doc/目录;
- 在common目录中的builder.py文件中,找到
LANGUAGES = ['en', 'fr']
修改为:
LANGUAGES = ['en', 'fr', 'zh']
- 新建zh子目录,并将en子目录下的tutorial目录复制到刚才新建的zh目录中 (如果是翻译其他文档,复制相应的目录);
- 修改zh目录下的conf.py文件:
- 在
import sys, os
这一行后 添加 两行:
reload(sys) sys.setdefaultencoding('utf8') - 在conf.py文件最后添加:
latex_preamble='\usepackage{ctex}'latex_premble+='\usepackage{ctex}\n\punctstyle{CCT}'
- 在
- 修改$SAGE/local/lib/python2.6/site-packages/Sphinx-0.6.3-py2.6.egg/sphinx/texinputs/Makefile文件,将其中的“pdflatex”全部替换为“xelatex”(共有5处);
- 将$SAGE/local/lib/python2.6/site-packages/Sphinx-0.6.3-py2.6.egg/sphinx/writers/latex.py中的“\\usepackage[utf8]{inputenc}”中的“utf8”修改为“latin1”,即“\\usepackage[latin1]{inputenc}”。
如果上述操作正常的话,就可以开始翻译了。将zh/tutorial下的所有.rst 文件翻译为中文后,即可进行编译。编译的方法如下:
- 转到$SAGE目录;
- 查看所有文档列表:
./sage -docbuild -D
此时应该可以看到“zh/tutorial”选项;
- 编译:
./sage -docbuild zh/tutorial html ./sage -docbuild zh/tutorial pdf
编译结果会在编译信息最后一行提示。
2010年6月21日更新:
以上是基于Sage 4.3所做的修改,今天下载了4.4.3,情况有些变化:
- 以上的第4、6步完全不需要了,因为相关的配置转移到其他文件中去了
- 修改$SAGE/devel/sage-main/doc/common/conf.py文件中两个地方:
-
latex_elements['inputenc'] = ‘\\usepackage[utf8x]{inputenc}’
改为
latex_elements['inputenc'] = ‘\\usepackage[latin1]{inputenc}’ - latex_elements['preamble']那一行下面再添加一行:
latex_elements['preamble'] += ‘\usepackage{ctex}\n\punctstyle{CCT}\n’
-
latex_elements['inputenc'] = ‘\\usepackage[utf8x]{inputenc}’
Zoundry Raven开源了
Zoundry Raven以及原来的Zoundry是我在Windows平台下最喜欢的Blog客户端程序。但是因为只有Windows平台的版本,所以后来还是ScribeFire用的多。刚刚知道Zoundry Raven开源了(消息来源:python编写的博客编写客户端Zoundry Raven开源)。过去看了一下,两个没想到,没想到今年1月份就已经开源了,我还以为是最近的事情;另一个没想到是,开源了大半年,居然还没有人移植到其他平台上。
SimPy
想用Python写一个仿真程序,网上的中文资料很少,比较完整的是IBM的这篇技术文章:
英文原版:Charming Python: SimPy simplifies complex models
中文版:可爱的 Python: SimPy 简化了复杂模型
本来是不错的文章,但是由于写的比较早(2002年12月26日),很多语句的用法在新版中发生了很大的变化。搞了一个晚上,程序勉强调通,但是那个记录最大最小时间的问题一直解决不了。实在搞不下去了,就到SimPy自带的doc中扒扒,没想到这个例子已经被收入正式的发行包中。具体位置在:/usr/share/doc/python-simpy-doc/SimPyModels/Market.py,如果是windows用户,请自己查找Market.py文件,应该是有的。
教训啊教训。
附Market.py原文:
import random
from math import sqrt
AISLES = 6 # Number of open aisles
ITEMTIME = 0.1 # Time to ring up one item
AVGITEMS = 20 # Average number of items purchased
CLOSING = 60*12 # Minutes from store open to store close
AVGCUST = 1500 # Average number of daily customers
RUNS = 8 # Number of times to run the simulation
SEED = 111333555 # seed value for random numbers
class Customer(Process):
def __init__(self):
Process.__init__(self)
# Randomly pick how many items this customer is buying
self.items = 1 + int(random.expovariate(1.0/AVGITEMS))
def checkout(self):
start = now() # Customer decides to check out
yield request, self, checkout_aisle
at_checkout = now() # Customer gets to front of line
waittime.tally(at_checkout-start)
yield hold, self, self.items*ITEMTIME
leaving = now() # Customer completes purchase
checkouttime.tally(leaving-at_checkout)
yield release, self, checkout_aisle
class Customer_Factory(Process):
def run(self):
while 1:
c = Customer()
activate(c, c.checkout())
arrival = random.expovariate(float(AVGCUST)/CLOSING)
yield hold, self, arrival
class Monitor2(Monitor):
def __init__(self):
Monitor.__init__(self)
self.min, self.max = (int(2**31-1),0)
def tally(self, x):
self.observe(x)
self.min = min(self.min, x)
self.max = max(self.max, x)
random.seed(SEED)
print ‘Market’
for run in range(RUNS):
waittime = Monitor2()
checkouttime = Monitor2()
checkout_aisle = Resource(AISLES)
initialize()
cf = Customer_Factory()
activate(cf, cf.run(), 0.0)
simulate(until=CLOSING)
print “Waiting time average: %.1f“ % waittime.mean(), \
“(std dev %.1f, maximum %.1f)” % (sqrt(waittime.var()),waittime.max)
print ‘AISLES:’, AISLES, ‘ ITEM TIME:’, ITEMTIME