Posts Tagged ‘python’

Python Notes(一)

一、为什么使用Python

想学Python不是一天两天了,但为什么要学这东西呢?

从功利的角度来看,Python能带来许多好处。特别是咱们学GIS的,看看James Fee总结的Esri新FAQ中是怎么说的。可以看到:

Q: Does ArcGIS 10 open up more functionality for use with Python?

A: Python integration is one of the key features of ArcGIS 10. At this release we’ve introduced a new Python subsystem called ArcPy, which exposes many of the ArcGIS functions.

Python是ArcGIS 10中重要的一部分,而且会有ArcPy这一子系统,估计是Geoproccesing的升级版吧。所以,这是趋势。

Q: Is VBA supported with ArcGIS Desktop 10?

A: Yes, ArcGIS Desktop 10 does support Microsoft VBA. However ArcGIS 10 is the last version with VBA support, so we encourage you to start the migration process. Python is an integral part of ArcGIS Desktop for automating tasks and the new add-in capabilities allow developers to easily create and deploy ArcMap customizations.

An important change at version 10 is that VBA is not part of the ArcGIS Desktop install. If you need VBA, you need to install the ArcObjects VBA SDK, which will setup the VBA Runtime, Editor, and Help. Please note that an additional authorization file is required for VBA. This is a no charge license that can be requested from ESRI Customer Service.

ArcGIS 10会支持VBA,但这是最后一代了。VBA没接触过,也幸好没接触啊。如果能用Python来写Add-in,那真是一件很惬意的事情。所以呢,学VBA不如学Python,而且只会VBA的也赶紧学Python吧。

Q: How is ArcGIS being integrated with Python statistics packages?

A: At the data level, ArcGIS 10 supports import and export of rasters to NumPy arrays; this is a starting point in many statistical analysis workflows. On the Geoprocessing Resource Center Model and Script Tool Gallery you will also find examples of using R in ArcGIS 10, and we expect to expand these samples throughout the year.

在数据层面上,ArcGIS 10会支持numpy这样的包。最近也用过numpy,是数值计算的好帮手。所以,感觉在ArcGIS中,会有越来越多的Python包可以使用。

看得出来,Python与ArcGIS的结合会越来越紧密,那作为一个GISer,你应该知道怎么做了吧。

然后从个人喜好的角度看,Google在用Python,豆瓣在用,还有EveryBlock也用。这几个毫不相干的东西因为Python的联系有一个共通的感觉,就是简洁。

最后,从Python本身来看,它是一门动态、解释型语言,与我掌握的C#可以相互补充。

还有一点,它是开源、免费的,在学习和使用过程中,和MS给你的那种感觉截然不同。简单说,没有了MSDN那种无微不至的关怀有时会无所适从,当然,同时也没有了使用盗版的罪恶感了。

总之,人生苦短,我用Python。当然,路途漫漫,刚刚上路而已。

二、几个Tip

近段时间,在学Python,在看哲思社区写的《可爱的Python》。本来当作入门书籍来看的,结果越看越不对劲,里面好多东西都是我未曾接触过的。不过作者开头就说了,这不是教材,当然也不是给你入门的了。这本书给我最大的收获就是,Python不用学,拿来用就是了。这是我最近才明白的一点,还是在没有看完的情况下。那么,我用它写个什么东西呢?我一直想不出。但在瞎捣腾的过程中,有几个地方还是值得注意一下的:

如何导入模块

python中导入模块使用的import语句:

import os
import sys

还有复杂点的就是:

import xx.yy
from xx import yy

但这些都是系统自带的,如果你自己写了个test.py,放在D:\\下,那该如何导入呢?

我暂时发现有两种方法,一是一劳永逸的,二是每次都得自己导入的。
  1. 你可以修改系统的环境变量中的PYTHONPATH。默认情况下是没有这个值的,所以可以这样操作:右键点击计算机-属性-高级系统设置-环境变量-XX的用户变量,新建一个“PYTHONPATH”用户变量,值为“D:\\”。
  2. 就是每次运行时动态添加:
    sys.path.append("D:\\")

    同样,你可以在sys.path中查看python导入模块会搜索的路径。

为字典增加项

在C#中,要为字典添加一项就是:

var dict = new Dictionary<string,int>();
dict.Add("a", 1);  

但在Python中,我找死也找不到Add方法。后来才发现这样就行了:

dict = {}
dict["a"] = 1
还有,有次我要个字符串的长度,也是想了半天Python的字符串怎么没有length属性呢?
结果,后来发现这样就行了:
len("i love beijing tiananmen square")
len是内置函数,不管是放个字符串还是数组进去,出来的都是长度。
好吧,我承认Python真的很简洁。

三、一个Demo

最近在看《什么是数学》,很科普,有点收获。什么是数学呢?按作者开篇说的,人类创造数就是用来数各种集合中对象的个数的,比方说茶几上有13个杯具,数清楚了,就是简单的数学。那在一块960万平方公里大的茶几上摆着13亿个杯具,用一些方法把这个快速、准确地数清楚了,也是数学。总之,我觉得吧,就是数数的学问。

我想做的一个Demo也是从这本书里看到的,里面有介绍素数定理,我太无知以前没有见过。

我是这么理解的,自然数中素数的分布是有规律的。令前n个自然数中素数的个数为An,那么An/n的值近似n的自然对数ln(n)的倒数,即1/ln(n)。

看到这里,又联系到在看的Python,就想用Python来验证验证,也算是一个小练习。

如何做呢?

  1. 写个生成素数的方法。
  2. 分别计算出An/n和1/ln(n)。
  3. 用图形来表示。

挺简单的吧,主要是用图形表示这块不了解怎么做,后来找到一个matplotlib这个包,挺不错的。

生成素数,prm.py:

import sys
import math
import numpy as np

def valslist(end,begin = 2):
    r = []
    for i in np.arange(begin,end,1):
        m = int(math.sqrt(float(i)))
        f = 1
        for j in np.arange(2,m+1):
            if i%j == 0:
                f = 0
                break
        if f == 1:
            r.append(i)
    return r

def count(end,begin = 2):
	return len(valslist(end,begin))
绘制素数分布,pnt.py:
import math
import numpy as np
import matplotlib.pyplot as plt
import prm

def show(nums):
	ns = np.arange(1,nums,1)
	l = []
	for n in ns:
		l.append(float(prm.count(n))/n)
	r = []
	for n in ns[1:]:
		r.append(1.0/math.log(n,math.e))
	plt.plot(ns,l,label="$An/n$",color="green",linewidth=2)
	plt.plot(ns[1:],r,"b-",label="$1/log(n)$",linewidth=2)
	plt.xlabel("n")
	plt.ylabel("val")
	plt.title("Prime Number Theorem")
	plt.legend()
	plt.show()
 效果:
pnt
从前1000个数来看,还是比较符合的。当然,数字越大,效果可能会更好,但是运算的速度。。。

四、结束

我是新手,又是菜鸟,所以错误难免会有,欢迎指教。

五、参考

用Python做科学计算-http://hyry.dip.jp/pydoc (此人牛得一塌糊涂)