python中xml文件处理的编码转换gb2312到utf-8

June 29th, 2006

的一些处理文件的包对于’‘,’gbk’等编码的文件一直支持的不好。 为此需要将这些编码的文件首先转换成容易处理的”″编码。 下面是一个编码格式为文件。我们用代的minidom包和一个第三方处理包elementtree分别进行处理。

file: test.
<? version=”1.0″ encoding=”″ ?>
<abc>
<doc>
编码测试!
</doc>
<doc>
编码再次!
</doc>
</abc>
利用minidom:

  1. import .dom.minidom
  2. fp = open("test.", "r")
  3. content = fp.read()
  4. fp.close()
  5. content = content.decode("").encode("")
  6. content = content.replace("encoding=""", "encoding="UTF-8"")
  7. dom = .dom.minidom.parseString(content)
  8. root = dom.documentElement
  9. for node in root.getElementsByTagName("doc"):
  10. rc = ""
  11. for node in node.childNodes:
  12. if node.nodeType in ( node.TEXT_NODE, node.CDATA_SECTION_NODE):
  13. rc = rc + node.data
  14. print rc.encode("")

利用elementtree

  1. from elementtree import ElementTree
  2. fp = open("test.", "r")
  3. content = fp.read()
  4. fp.close()content = content.decode("").encode("")
  5. content = content.replace("encoding=""", "encoding="utf-8"")
  6. root = ElementTree.fromstring(content)
  7. iter = root.findall(".//doc")
  8. for element in iter:
  9.     print element.text.encode("")

This post has been viewed 219 times.

Tags: , , , ,

Related posts


python使用字典,集合点滴

December 22nd, 2005

1. 去除类似在代码中输入中文就出现“sys:1: DeprecationWarning: Non-ASCII character “xb9″ in file test1.py on line 11, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details”这样的警告,这需要在源代码的开始添加下面两行代码就可以了:

# /usr/bin/
# -*- coding: GB18030 -*-

其中 GB18030,可以替换成cp936,或者其他汉字编码规范都可以。

Title: Sorting dictionaries by value in 2.4
Submitter: Nick Coghlan (other recipes)
Last Updated: 2004/09/13
Version no: 1.0
Category: Searching

5 stars 2 vote(s)

Description:

2.4 adds a new builtin function sorted(), which can make obtaining the items of a dictionary sorted by key or value a single line operation.

Source: Text Source

# Example from PEP 265 - Sorting Dictionaries By Value
# Counting occurences of letters

d = {”a”:2, “b”:23, “c”:5, “d”:17, “e”:1}

# operator.itemgetter is new in 2.4
# `itemgetter(index)(container)` is equivalent to `container[index]`
from operator import itemgetter

# Items sorted by key
# The new builtin `sorted()` will return a sorted copy of the input iterable.
print sorted(d.items())

# Items sorted by key, in reverse order
# The keyword argument `reverse` operates as one might expect
print sorted(d.items(), reverse=True)

# Items sorted by value
# The keyword argument `key` allows easy selection of sorting criteria
print sorted(d.items(), key=itemgetter(1))

# In-place sort still works, and also has the same new features as sorted
items = d.items()
items.sort(key = itemgetter(1), reverse=True)
print items

2.4 的 Alpha 2 版本在8月5号已经放出来了, 今天才有点时间去看。尝鲜之后,和大家分享。
首先引起我注意的是,2.4 中把 set集合 类型内置在语言中了,以前是放在标准库里面。现在的使用方法也很灵活方便:
(文中示例一部分摘自 .org 网站)
>>> a = set(”abracadabra”) # 由字符串生成一个 set
>>> “z” in a # 快速检测成员是否存在
False
>>> a
set([”a”, “r”, “b”, “c”, “d”])
>>> “”.join(a) # 将set 中的元素转化回 字符串
“arbcd”

>>> b = set(”alacazam”) # 另一个 set
>>> a - b # 得到属于A 而 不属于 B 的元素组成的 set
set([”r”, “d”, “b”])
>>> a | b # a 与 b 的并集
set([”a”, “c”, “r”, “d”, “b”, “m”, “z”, “l”])
>>> a & b # a 与 b 的交集
set([”a”, “c”])
>>> a ^ b # 属于 a 或 b 但不属它们交集 的元素
set([”r”, “d”, “b”, “m”, “z”, “l”])

>>> a.add(”z”)
>>> a.update(”wxy”)
>>> a
set([”a”, “c”, “b”, “d”, “r”, “w”, “y”, “x”, “z”])
>>> a.remove(”x”) # 删除集合中一个元素
>>> a
set([”a”, “c”, “b”, “d”, “r”, “w”, “y”, “z”])

This post has been viewed 187 times.

Tags: ,

Related posts


在Windows环境下用Editplus打造一个Python编辑调试环境

September 25th, 2005

图文格式请下载下面的文件。

http://lwkj.blogchina.com/inc/editplus-python.pdf

 

有很多集成开发工具,商业的有Boa等,还有自带的集成环境IDLE下还有Pythonwin等。但是,这些工具有的是过于复杂,有的是对Unicode支持的不太好。因此,今天我们利用一个很流行的,功能也非常强大的文本编辑软件,改造成一个能够很好的支持编辑,浏览,运行及调试的开发环境,并且具备语法加亮,自动完成,自动缩进,新建文件模板等功能支持。我们用的v2.202.4版。

1.要使能够运行程序,首先打开tools->Preferences对话框,在User tools里新建一个group,名字我们叫,在 group里新建一个工具也起名为,分别在Menu text:填入,在Command:填入的安装路径,Argument:填入$(FileName)Initial Directory:填入$(FileDir)。完成这一步的结果如下图(1):

 

 

(1)

 

这样我们在里打开一个文件,在tools菜单下就会有一个选项,直接单击就可以运行程序了,也可以利用快捷键(Ctrl1),根据你设置用户工具的个数,这个快捷键可能有所不同。如下图(2):

 

(2)

 

在此处我们想实现下面的一个功能:就是当程序出错的时候,解释器会给出类似如下的提示信息:

———- ———-

File “test.py”, line 6

print “a

^

SyntaxError: EOL while scanning single-quoted string

 

Output completed (1 sec consumed) - Normal Termination

 

此时,我们一般会根据提示的行号到文本中去找错误的地方,而不能够象其他的编译器一样直接双击错误的提示,将光标直接移动到错误行。此时如果我们直接双击某行,则会出现找不到某文件的错误。此处,我们就利用Output Pattern的实现这个功能。具体做法如下,在图(1)中的Capture Output选项前的复选框要选上,然后打开Output Pattern按钮,在Output Pattern对话框中,首先取消Use default output pattern选项前的复选框,在Regular expression栏里填入正则表达式如下:

File “(.+)”, line ([0-9]+)

File Name栏里选择Tagged expression 1

Line栏里选择Tagged expression 2

Column栏里为None

结果如图(3):

 

(3)

然后我们直接双击错误提示信息行

File “test.py”, line 6

光标就会直接跳到第六行,非常的方便,尤其是当多个文件互相调用的时候,这种方法可以方便打开文件找到错误的位置。

2.为了实现语法加亮和自动完成功能,我们必须下载两个文件,下载地址为

http://www.editplus.com/files/pythonfiles.zip ,解压到的安装目录下。压缩包有三个文件,此处我们用到两个,.acp文件和python_extd.stx文件。Acp文件是自动完成文件,stx文件是语法加亮文件。怎样加载呢?方法如下:

tools->preferences->Setting & syntax下,首先新建一个文件类型,我们命名为,扩展名(file extensions)栏里我们填入py。在syntax file栏里我们找到刚才下载的python_extd.stx文件,在Auto completion栏里找到.acp文件,在Function Pattern栏里填入:

[ ]*def[ ].+:

这样我们就可以通过CtrlF11快捷键直接显示出文件中的函数列表。设置完成如下图(4):

 

(4)

 

这时我们打开一个文件,就可以看到有语法加亮了。但是我们在编辑的时候会发现一个问题就是,在输入冒号后,没有自动缩进,当然,如果我们手工缩进后会发现后面的输入也进行了同样的缩进,怎样让自动识别冒号然后直接缩进,并且如何修改缩进的长度呢?在图(4)中,我们可以看到一个Tab/Indent标签,打开他可以看到TabIndent的选项,分别填入自己习惯的距离。我两个都填入4,并且选中Insert spaces instead of tabEnable auto indent。然后在Auto Indent open里填入一个冒号“:”。完成设置以后如下图(5):

 

 

(5)

其他的设置也可以根据类似的设置进行。

3.还有一点很方便的是,可以通过建立一个文件的模板,来快速新建一个文件。首先我们建立一个名为template.py的文件,内容自定,我们这里假设如下:

�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D

“”"

Usage:

 

“”"

�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D�D

保存,将template.py文件放到安装目录下。

Tools->preferences->templates

打开模板设置对话框,首先添加一个名为的模板,把file path设置到我们刚才建立的template.py文件上。配置结果如图(6):

 

图(6

点击load按钮。完成。这样在file->New->下就会有一个模板,直接可以方便的建立一个文件。

至此,已经可以方便的编辑,浏览,调试和运行程序了。最后还要提醒一点的是,个人使用习惯不同,可以根据类似的方法进行修改和调整。通过以上的介绍,我们可以看出,可以很方便的配置,能够完成常用的大部分功能,有效的提高编程效率。

This post has been viewed 159 times.

Tags: , , , , ,

Related posts


阅读Python Tutorial

September 4th, 2005

这几天间断的看了最新的 Tutorial,觉得这个是最好的入门教材。英语的语法也比较简单,其中还有一些简单易懂的例子。如果英文不太顺利的,可以找到刘鑫的译本,双语对照的,翻译的相当工整,基本上挑不出什么毛病,只有极其个别的语法上的小错误,但是这些小小的错误根本就不影响阅读,尤其是当读到不太通顺的地方,可以参看原文获得正确的理解。
比如,“raw mode”作者翻译成“行模式”,我觉得翻译成“原生模式”,
“in the next chapter, the mechanics of using the interpreter are explained”,作者翻译成“在下一章,我们会很机械的说明解释器的用法”,我觉得翻译成“在下一章我们将会介绍解释器的机制”;”reverse quotes(`)”作者翻译成“相对而言引号”,正确译法为“反引号”;等。
不过,我从作者的翻译中学习到不少的东西, Tutorial的翻译也是一篇优秀的翻译。

This post has been viewed 115 times.

Tags:

Related posts


什么是wxPython

July 28th, 2005

What is ?
什么是?

is a GUI toolkit for the programming language. It allows programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a extension module (native code) that wraps the popular wxWidgets cross platform GUI library, which is written in C++.
是一个编程语言的GUI工具包。他能够支持程序员利用一种健壮的,高功能的图形用户界面进行创作程序,简洁且简单。他是的一个扩展模块,该模块封装了流行的wxWidgets跨平台的GUI库,该库是由C++所写。

Like and wxWidgets, is Open Source, which means that it is free for anyone to use and the source code is available for anyone to look at and modify. And anyone can contribute fixes or enhnacments to the project.
和wxWidgets一样,也是开放源代码的,这意味着任何人都可以免费使用,可以看,可以修改他的源代码。并且,每个人也可以为这个项目贡献他的智慧。

is a cross-platform toolkit. This means that the same program will run on multiple platforms without modification. Currently supported platforms are 32-bit Microsoft , most Unix or unix-like systems, and Macintosh OS X.
是一个跨平台的工具包,这意味着相同的程序可以运行在多个平台上而不用修改。目前,支持的平台是32-bit的Microsoft ,大多数Unix和类Unix系统,以及Macintosh操作系统。

Since the language is , programs are simple, easy to write and easy to understand.
由于所用语言是程序简洁,简单易写并且易与理解。

Overview
概述

To set a application going, you will need to derive an App class and override App.OnInit.
为了运行一个一个应用程序,你必须从App类中派生一个类,并且重载App.OnInit方法。

An application must have a top-level Frame or Dialog window. Each frame may contain one or more instances of classes such as Panel, SplitterWindow or other and controls.
一个应用程序必须有一个顶级Frame或者Dialog窗口。每一个Frame可以包含一个或者多个类的实例,比如Panel,SplitterWindow或者其他的窗口或者控件。

A frame can have a MenuBar, a ToolBar, a status line, and an Icon for when the frame is iconized.
一个Frame可以有一个MenuBar,一个ToolBar,一个状态栏和该标志该Frame的图标。

A Panel is used to place controls (classes derived from Control) which are used for user interaction. Examples of controls are Button, CheckBox, Choice, ListBox, RadioBox, Slider.
一个Panel可以用来放置控件(从Cotrol派生出的类),这些控件被用来和用户交互。一些controls的例子:Button,CheckBox,Choice,ListBox,RadioBox,Slider等。

Instances of Dialog can also be used for controls, and they have the advantage of not requiring a separate frame.
一个对话框实例也可以用来放置controls,并且他们具有不需要一个单独的Frame的优点。

Instead of creating a dialog box and populating it with items, it is possible to choose one of the convenient common dialog classes, such as MessageDialog and FileDialog.
不用直接创建一个对话框并组合多个items,我们可以选一个方便的通用的对话框类,比如MessageDialog类和FileDialog类。

You never draw directly onto a window. Instead, you use a device context (DC). DC is the base for ClientDC, PaintDC, MemoryDC, PostScriptDC, MemoryDC, MetafileDC and PrinterDC. If your drawing functions have DC as a parameter, you can pass any of these DCs to the function, and thus use the same code to draw to several different devices. You can draw using the member functions of DC, such as DC.DrawLine and DC.DrawText. Control colour on a window (Colour) with brushes (Brush) and pens (Pen).
你永远不能直接中窗口中直接绘画,反之,你是利用device context(DC)。DC是ClientDC,PaintDC, MemoryDC, PostScriptDC, MemoryDC, MetafileDC和PrinterDC的基类。如果你的一个绘图函数有一个参数是DC,你可以传递上述的任意一个DC给这个函数,并且可以利用相同的代码画出几个不同的Devices。你可以利用DC的从成员函数绘图,比如DC.DrawText。窗口上(颜色)Control的颜色利用brushes(Brush)和pens(Pen)。

Most modern applications will have an on-line, hypertext help system; for this, you need Help and the HelpController class to control Help.
大多数最新的应用程序都有一个在线的,超文本帮助系统,为此,你需要Help和HelpController类来控制Help。

GUI applications aren”t all graphical wizardry. You”ll also need lists and hash tables. But since you”re working with , you should use the ones provides (list, tuple, dict), rather than the wxWidgets versions. Same goes for the database related classes. The basic rule of thumb is this: If you can do it directly in , you probably should. If there is a reason not to use a data type, will provide a wrapper for the wxWidgets class.
GUI应用程序不是所有图形的巫术,你也需要列表和哈希表等。但是,你是利用工作,你应当用提供的之一(list, tuple, dict),而不是wxWidgets版本的。用到的数据库相关类是相同的。一个基本原则是:如果你可以直接利用完成,那么你应该利用。如果有一个理由你不适用的数据类型,将要提供一个wWidgets类的封装。

This post has been viewed 145 times.

Tags: ,

Related posts


利用Python写一个简单的汉语句子分割器

May 28th, 2005

主要用到两个知识点:

(1)正则表达式的用法

(2)Unicode编码的用法。

=========================================

比如要实现一个汉语句子分割器,比如,我们可以设定以下结尾的都分句。

。 ! ? 。” !” ?”

当然,还可以添加其他的结束标志,我们将把以结束标志结尾的句子都分割称单独的句子。

我利用正则表达式
expression = r”。|!|?|。”|!”|?””

listSentence = re.split(expression, sentence)

但是这样情况下,就会把汉字中某些字分开称乱码,比如:

假如

str1 = “【幸福】的人是很少的。”

这样一个字符串就会被分开,因为“福”的后一半“】”的前一半正好是a3a1是一个“!”。当然,类似的情况肯定还有。

若想解决这个问题必须,对字符串对象进行Unicode转换。具体的方法如下:

----------------------------------

import re

expression = unicode (”。”|!”|?”|。|!|?”, “cp936″)

string1 = unicode (”随着信息。”技术的发展,计算机应用渗透到社会生活的各个领域,特别是在电子商务中的应用,使人们对信息的依赖程度越来越大,从而使信息安全技术显得格外重要。信息安全技术主要是研究计算机系统信息的机密性、完整性、可获取性和真实性,它的核心是加密技术。加密技术根据加密密钥与解密密钥是否相同可分为对称加密技术(单密钥加密技术)和非对称加密技术(公开密钥加密技术)。加个叹号!加个问号?试试句号加引号。“试试叹号加引号!”。“试试问号加引号?” 加点废话”, “cp936″)

listSentence = re.split(expression, string1)

for sent in listSentence:
print sent
----------------------------------

这样就可以避免两个汉字字符的中间产生错开的情况,而避免了上面提到的情况。

但是,如果我们想把分完句的结果写道文件中去,

----------------------------------

import re

expression = unicode (”。”|!”|?”|。|!|?”, “cp936″)
string1 = unicode (”随着信息。”技术的发展,计算机应用渗透到社会生活的各个领域,特别是在电子商务中的应用,使人们对信息的依赖程度越来越大,从而使信息安全技术显得格外重要。信息安全技术主要是研究计算机系统信息的机密性、完整性、可获取性和真实性,它的核心是加密技术。加密技术根据加密密钥与解密密钥是否相同可分为对称加密技术(单密钥加密技术)和非对称加密技术(公开密钥加密技术)。加个叹号!加个问号?试试句号加引号。“试试叹号加引号!”。“试试问号加引号?” 加点废话”, “cp936″)

listSentence = re.split(expression, string1)

ofile = open(”resu.txt”, “w”)
for sent in listSentence:
print sent
ofile.write(sent)
ofile.close()

------------------------------------

则会出现类似:

ofile.write(sent)
UnicodeEncodeError: “ascii” codec can”t encode characters in position 0-3: ordinal not in range(128)

这样的错误。

解决办法参考:

http://www.donews.net/limodou/articles/285118.aspx

具体的代码如下:

---------------------

import re

expression = unicode (”。”|!”|?”|。|!|?”, “cp936″)
string1 = unicode (”随着信息。”技术的发展,计算机应用渗透到社会生活的各个领域,特别是在电子商务中的应用,使人们对信息的依赖程度越来越大,从而使信息安全技术显得格外重要。信息安全技术主要是研究计算机系统信息的机密性、完整性、可获取性和真实性,它的核心是加密技术。加密技术根据加密密钥与解密密钥是否相同可分为对称加密技术(单密钥加密技术)和非对称加密技术(公开密钥加密技术)。加个叹号!加个问号?试试句号加引号。“试试叹号加引号!”。“试试问号加引号?” 加点废话”, “cp936″)

listSentence = re.split(expression, string1)

ofile = open(”resu.txt”, “w”)
ofile.write(”
“.join(listSentence).encode(”cp936″))
ofile.close()

---------------------

需要注意一点的是:

要注意分割标点的顺序,如果是把。放在了。”前面,那么就会先匹配。,这样的化, 。”就永远不会匹配到了。

感谢-Chinese各位朋友的帮助。

This post has been viewed 163 times.

Tags: , ,

Related posts


some bases METHODS

May 24th, 2005

METHODS
object.__eq__(self, other)
__eq__(self, other)方法

Return a Boolean comparison between self and other. Determines how a datatype responds to the == operator. The parent class object does not implement . __eq__() since by default object equality means the same thing as identity (the is operator). A child is free to implement this in order to affect comparisons.
返回一个self和other比较的布尔值,决定了一个数据类型如何应答==操作符。其父类object没有实现.__eq__()方法,因为缺省对象的等同性意味着相同的事物。子类可以自由的实现他以实现不同的比较。

object.__ne__(self, other)
__ne__(self, other)方法

Return a Boolean comparison between self and other. Determines how a datatype responds to the != and <> operators. The parent class object does not implement .__ne__() since by default object inequality means the same thing as nonidentity (the is not operator). Although it might seem that equality and inequality always return opposite values, the methods are not explicitly defined in terms of each other. You could force the relationship with:
返回一个self和other比较的布尔值,决定了一个数据类型如何应答!= 和 <> 操作符。其父类object没有实现.__ne__()方法,因为缺省对象的不等同性意味着不相同的事物。尽管他看起来相等和不等经常返回一个相反的值,这些方法没有显式的定义他们,你可以强制他们的关系:

>>> class EQ(object):
… # Abstract parent class for equality classes
… def __eq__(self, o): return not self <> o
… def __ne__(self, o): return not self == o

>>> class Comparable(EQ):
… # By def”ing inequlty, get equlty (or vice versa)
… def __ne__(self, other):
… return someComplexComparison(self, other)

object.__nonzero__(self)
__nonzero__(self)方法

Return a Boolean value for an object. Determines how a datatype responds to the Boolean comparisons or, and, and not, and to if and filter(None,…) tests. An object whose .__nonzero__() method returns a true value is itself treated as a true value.
返回一个对象的布尔值。决定了一个数据类型如何应答一个布尔比较or, and , not 和filter(none,..)。一个对象whose.__nonzeor__()方法返回一个真值如果他本身被认为是一个真值的话。

object.__len__(self)
len(object)

Return an integer representing the “length” of the object. For collection types, this is fairly straightforward―how many objects are in the collection? Custom types may change the behavior to some other meaningful value.
返回表示一个对象长度的整数值。对于集合类型,这是非常有用的――在集合中有多少个对象?自定义类型可能改变其他这种行为到其他一些有意义的值。

object.__repr__(self)
repr(object)
object.__str__(self)
str(object)

Return a string representation of the object self. Determines how a datatype responds to the repr() and str() built-in functions, to the print keyword, and to the back-tick operator.
返回一个表示对象自身的字符串形式。决定了如何应答repr()和str()内建函数的方法。

Where feasible, it is desirable to have the .__repr__() method return a representation with sufficient information in it to reconstruct an identical object. The goal here is to fulfill the equality obj==eval(repr(obj)). In many cases, however, you cannot encode sufficient information in a string, and the repr() of an object is either identical to, or slightly more detailed than, the str() representation of the same object.
可以灵活的运用__repr__()方法返回一个包含有足够信息的对于同一个对象的重建,这里的目标就是实现一个相等的对象:obj == eval(repr(obj))。在许多情况下,然而,你不能把足够的信息编码成字符串,那么repr()同样也不能,或者更为详细一点的,str()表示一个相同的对象。

This post has been viewed 116 times.

Tags:

Related posts


TOPIC

May 24th, 2005

TOPIC — Base Classes for Datatypes

话题――基类的数据类型

——————————————————————–

There are several magic methods that are often useful to define for -any- custom datatype. In fact, these methods are useful even for classes that do not really define datatypes (in some sense, every object is a datatype since it can contain attribute values, but not every object supports special syntax such as arithmetic operators and indexing). Not quite every magic method that you can define is documented in this book, but most are under the parent datatype each is most relevant to. Moreover, each new version of has introduced a few additional magic methods; those covered either have been around for a few versions or are particularly important.

有几个有魔力的方法,他们经常用来定义任意自定义的类型。实际上,这些方�?br> 对于那些没有真正定义数据类型的类也是有用的(在某种程度上,每一个对象就是一个数据类型,因为他可能包含多个属性值,但是不是每一个对象都支持操作符运算和索引语法)。在本书中,并不对每一个这样的方法进行详细介绍,但�?br> 大部分都和他们的父类型相关。而且,每一个的新版本都会引入一些新�?br> 这样有魔力的方法;那些仅仅覆盖几个版本的方法就不是很重要了.

In documenting class methods of base classes, the same general conventions are used as for documenting module functions. The one special convention for these base class methods is the use of “self” as the first argument to all methods. Since the name “self” is purely arbitrary, this convention is less special than it might appear. For example, both of the following uses of “self” are equally legal:

在基类的文档类方法中,那些文档模块函数也适用于相同的通用惯例。丢于这�?br> 基类方法的一个特殊的惯例是利用self作为所有方法的第一个参数。因为self 这个名字是任意取的,这个惯例比他显示的要普通。比如,下面的都用self在逻辑上是等同的:

>>> import string>>> self = "spam">>> object.__repr__(self)"<str object at 0x12c0a0>">>> string.upper(self)"SPAM"

However, there is usually little reason to use class methods in place of perfectly good built-in and module functions with the same purpose. Normally, these methods of datatype classes are used only in child classes that override the base classes, as in:

然而,利用完全的built-in和模块函数代替类的方法通常也没有太多的理由�?br> 通常,这些数据类型类的方法仅仅在子类中重载基类,如下:

>>> class UpperObject(object):...       def __repr__(self):...           return object.__repr__(self).upper()...>>> uo = UpperObject()>>> print uo<__MAIN__.UPPEROBJECT OBJECT AT 0X1C2C6C>

This post has been viewed 104 times.

Tags:

Related posts


wingIDE和Komodo中的AutoComplete比较

May 21st, 2005

这两个集成开放环境()都非常优秀,界面优雅且博采众长,术业专攻,只针对语言。在使用的过程中,发现两者的AutoComplete功能,也就是自动完成功能各有所长,各有所短。

能够有效的把所定义的所有变量、函数和类以及自带的所有模块的函数都能够自动的现实出来。比如利用正则表达式re模块的时候,我们输入:re.sp的时候就会自动提示re.split,但是括号还需要自己输入,另外,在输入第一个括号的时候,不能够提示该函数所需的变量。这一点就实现的比较体贴,当你输入括号的时候,就会提示该函数有几个变量,每一个变量是什么含意。

但是的自动提示功能好像不是特别的完善,尤其是对于刚刚前面刚刚定义的变量和函数,有时候不能够提示。这一点做的就非常出色。

This post has been viewed 125 times.

Tags: , , , ,

Related posts


话题―― 特化的Python数据类型

May 18th, 2005

TOPIC — Specializing Datatypes

话题―― 特化的数据类型

——————————————————————–

comes with an excellent collection of standard datatypes–Appendix A discusses each built-in type. At the same time, an important principle of programming makes types less important than programmers coming from other languages tend to expect. According to ”s “principle of pervasive polymorphism” (my own coinage), it is more important what an object -does- than what it -is-. Another common way of putting the principle is: if it walks like a duck and quacks like a duck, treat it like a duck.

具有优秀的标准数据类型的集合――附录A讨论了每一个内建类型。与此同时,和别的编程语言相比,编程中一个重要的原则就 是降低了数据类型的重要性。根据的“深入多态现象”(作者自己构造的术语),一个对象做什么要比一个对象是什么重要。另外一种 表述该原则就是:如果它走起路来像一只鸭子,并且叫起来也像一只鸭子,那么就把它当作像一只鸭子处理。

Broadly, the idea behind polymorphism is letting the same function or operator work on things of different types. In C++ or Java, for example, you might use signature-based method overloading to let an operation apply to several types of things (acting differently as needed). For example:

广泛的,多态性背后的思想就是使相同的函数和操作符能够处理不同类型的事物。在C++或者Java中,比如,你可能利用基于信号的方法重载,使一个操作能够应用于多种类型(在需要的时候自动适应)。比如:

#———— C++ signature-based polymorphism ———–#
#include <stdio.h>
class Print {
public:
void print(int i) { printf(”int %d
“, i); }
void print(double d) { printf(”double %f
“, d); }
void print(float f) { printf(”float %f
“, f); }
};
main() {
Print *p = new Print();
p->print(37); /* –> “int 37″ */
p->print(37.0); /* –> “double 37.000000″ */
}

最直接的关于基于信号重载函数的一个实现就是检查参数,可以简单的写成:

#——- “signature-based” polymorphism ———–#
def Print(x):
from types import *
if type(x) is FloatType: print “float”, x
elif type(x) is IntType: print “int”, x
elif type(x) is LongType: print “long”, x
Writing signature-based functions, however, is extremely un-Pythonic. If you find yourself performing these sorts of explicit type checks, you have probably not understood the problem you want to solve correctly! What you -should- (usually) be interested in is not what type “x” is, but rather whether “x” can perform the action you need it to perform (regardless what type of thing it is strictly).

然而,编写基于信号的函数是极度非化的。如果你发现你使用这种显式的类型检查,有可能还没有正确理解你将要解决的问题!你――应该――(通常)感兴趣的不是‘x’是什么,而是‘x’是否可以执行你需要的操作(不管它实际上是什么类型)。

This post has been viewed 97 times.

Tags:

Related posts