存档

文章标签 ‘Python’

[python]一个python的个人记账程序

2010年4月9日 没有评论

一个python的个人记账程序

http://code.google.com/p/youmoney/

界面不错,功能也不错,可以用作学习参考

分类: Mywitter 标签:

IndentationError: unindent does not match any outer indentation level

2010年3月24日 没有评论

果然是缩进的问题
参见[http://www.cnblogs.com/dczsf/archive/2009/03/06/1404515.html]
郁闷了一会儿,我本来想定义一个类对象的成员变量,结果出现了这样的问题,我还以为是语法错误呢

Python中分类的成员变量和对象的成员变量
类的成员变量和C++中的静态成员变量相同,由该类的所有对象(实例)共享。
对象的成员变量和C++中的普通成员变量相同,由对象(实例)独享
阅读全文…

分类: 编程技术 标签:

Python列出目录树并实现排序

2010年3月11日 没有评论

指定目录排序列出目录树并写入文件中

#! /usr/bin/env python
 
import os
import sys
 
def list_and_sort( path ):
    dirs = sorted([d for d in os.listdir(path) if os.path.isdir(path + os.path.sep + d)])
    dirs.extend(sorted([f for f in os.listdir(path) if os.path.isfile(path + os.path.sep + f)]))
    return dirs;
 
def listdir(space, dir,file):
    if space == '':
        file.write(dir + '\n' )
    prev = space
#list = os.listdir(dir)
    list = list_and_sort( dir )
    for line in list:
        filepath = os.path.join(dir,line)
        if os.path.isdir(filepath):
            if line.find( '.svn' ) >= 0:
                continue
            space = prev + '--'
            file.write( space + line + '\n' )
            listdir( space, filepath, myfile )
        elif os.path:
            ext = os.path.splitext(os.path.join(line) )[1].lower()
            if ext == '.o':
                continue
            space = prev + '--'
            myfile.write( space + line + '\n' )
 
dir = raw_input('please input the path:')
myfile = open('filelist.txt','w')
listdir( '', dir, myfile )
分类: 编程技术 标签: , ,

indent格式化目录下的程序文件(含indent配置)

2010年2月5日 没有评论

indent格式化目录下的所有文件(含indent配置)

一段python脚本,整理指定目录下的所有.cpp,.h,.c文件
python代码
import os
import sys
def walk_dir(dir,fileinfo,topdown=True):
  for root, dirs, files in os.walk(dir, topdown):
    for name in files:
      ext = os.path.splitext(os.path.join(name) )[1].lower()
      if ext == '.cpp' or ext == '.h' or ext == '.c':
        print( os.path.join(name))
        os.system( 'indent ' + os.path.join(root, name) )
        fileinfo.write( '  ' + os.path.join(root, name) + '\n')
 
dir = raw_input('please input the path:')
fileinfo = open('list.txt','w')
walk_dir(dir,fileinfo)
indent配置
-bad -bap -bbb -bbo -nbc -bl -bli0 -bls -c33 -cd33 -ncdb -ncdw -nce -cli0 -cp33 -cs -d0 -nbfda -nfc1 -nfca -hnl -ip5 -l80 -lp -prs -saf -sai -saw -nsc -nsob -nss -i4 -ts4 -nut -npcs -npsl

阅读全文…

分类: 编程技术 标签: , ,

【转】Python中使用中文

2009年8月11日 没有评论

python的中文问题一直是困扰新手的头疼问题,这篇文章将给你详细地讲解一下这方面的知识。当然,几乎可以确定的是,在将来的版本中,python会彻底解决此问题,不用我们这么麻烦了。

先来看看python的版本:
>>> import sys
>>> sys.version
'2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)]'

(一)
用记事本创建一个文件ChineseTest.py,默认ANSI:
s = “中文”
print s

测试一下瞧瞧:
E:\Project\Python\Test>python ChineseTest.py
File “ChineseTest.py”, line 1
SyntaxError: Non-ASCII character '\xd6' in file ChineseTest.py on line 1, but no encoding declared; see http://www.pytho
n.org/peps/pep-0263.html for details

偷偷地把文件编码改成UTF-8:
E:\Project\Python\Test>python ChineseTest.py
File “ChineseTest.py”, line 1
SyntaxError: Non-ASCII character '\xe4' in file ChineseTest.py on line 1, but no encoding declared; see http://www.pytho
n.org/peps/pep-0263.html for details

无济于事。。。
既然它提供了网址,那就看看吧。简单地浏览一下,终于知道如果文件里有非ASCII字符,需要在第一行或第二行指定编码声明。把ChineseTest.py文件的编码重新改为ANSI,并加上编码声明:
# coding=gbk
s = “中文”
print s

再试一下:
E:\Project\Python\Test>python ChineseTest.py
中文

正常咯:)
(二)
看一看它的长度:
# coding=gbk
s = “中文”
print len(s)
结果:4。
s这里是str类型,所以计算的时候一个中文相当于两个英文字符,因此长度为4。
我们这样写:
# coding=gbk
s = “中文”
s1 = u”中文”
s2 = unicode(s, “gbk”) #省略参数将用python默认的ASCII来解码
s3 = s.decode(“gbk”) #把str转换成unicode是decode,unicode函数作用与之相同
print len(s1)
print len(s2)
print len(s3)
结果:
2
2
2
(三)
接着来看看文件的处理:
建立一个文件test.txt,文件格式用ANSI,内容为:
abc中文
用python来读取
# coding=gbk
print open(“Test.txt”).read()
结果:abc中文
把文件格式改成UTF-8:
结果:abc涓枃
显然,这里需要解码:
# coding=gbk
import codecs
print open(“Test.txt”).read().decode(“utf-8″)
结果:abc中文
上面的test.txt我是用Editplus来编辑的,但当我用Windows自带的记事本编辑并存成UTF-8格式时,
运行时报错:
Traceback (most recent call last):
File “ChineseTest.py”, line 3, in <module>
print open(“Test.txt”).read().decode(“utf-8″)
UnicodeEncodeError: &apos;gbk&apos; codec can&apos;t encode character u&apos;\ufeff&apos; in position 0: illegal multibyte sequence

原来,某些软件,如notepad,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。
因此我们在读取时需要自己去掉这些字符,python中的codecs module定义了这个常量:
# coding=gbk
import codecs
data = open(“Test.txt”).read()
if data[:3] == codecs.BOM_UTF8:
data = data[3:]
print data.decode(“utf-8″)
结果:abc中文

(四)一点遗留问题
在第二部分中,我们用unicode函数和decode方法把str转换成unicode。为什么这两个函数的参数用”gbk”呢?
第一反应是我们的编码声明里用了gbk(# coding=gbk),但真是这样?
修改一下源文件:
# coding=utf-8
s = “中文”
print unicode(s, “utf-8″)
运行,报错:
Traceback (most recent call last):
File “ChineseTest.py”, line 3, in <module>
s = unicode(s, “utf-8″)
UnicodeDecodeError: &apos;utf8&apos; codec can&apos;t decode bytes in position 0-1: invalid data
显然,如果前面正常是因为两边都使用了gbk,那么这里我保持了两边utf-8一致,也应该正常,不至于报错。
更进一步的例子,如果我们这里转换仍然用gbk:
# coding=utf-8
s = “中文”
print unicode(s, “gbk”)
结果:中文
翻阅了一篇英文资料,它大致讲解了python中的print原理:
When Python executes a print statement, it simply passes the output to the operating system (using fwrite() or something like it), and some other program is responsible for actually displaying that output on the screen. For example, on Windows, it might be the Windows console subsystem that displays the result. Or if you&apos;re using Windows and running Python on a Unix box somewhere else, your Windows SSH client is actually responsible for displaying the data. If you are running Python in an xterm on Unix, then xterm and your X server handle the display.

To print data reliably, you must know the encoding that this display program expects.

简单地说,python中的print直接把字符串传递给操作系统,所以你需要把str解码成与操作系统一致的格式。Windows使用CP936(几乎与gbk相同),所以这里可以使用gbk。
最后测试:
# coding=utf-8
s = “中文”
print unicode(s, “cp936″)
结果:中文
========================

本文转自Python邮件列表:[CPyUG:47963] python unicode 和 中文 (zz,不知道原作者了)
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/kernelspirit/archive/2008/07/14/2650696.aspx

分类: 默认分类 标签: , , ,