Tuesday, July 06, 2010

Android Scripting Environment (ASE)

开源项目
http://code.google.com/p/android-scripting/
能让Python,Perl等脚本语言运行在Android系统上,目前还是alpha版本.

首先安装ase_r25.apk
python_extras_r7.zip
python_r7.zip
python_scripts_r7.zip
放到你的SDCrad的根目录下.
打开ASE, menu -> view -> Interpreters -> menu -> Add -> Python
会在SDCrad的根目录下新建ase文件夹
将上面的三个zip包解压到ase文件夹

然后就可以运行python的测试程序了

Tags: Android, Python


Friday, May 07, 2010

python minidom

import xml.dom.minidom

test = """
<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>
<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>
</bookstore>
"""

def getTagText(root, tag):
    node = root.getElementsByTagName(tag)[0]
    rc = ""
    for node in node.childNodes:
        if node.nodeType in ( node.TEXT_NODE, node.CDATA_SECTION_NODE):
            rc = rc + node.data
    return rc

def toStr(root, num):
    if num==0:
        print root.nodeName
    for node in root.childNodes:
        if node.nodeType == node.ELEMENT_NODE:
            value = getTagText(root,node.nodeName)
            if value != '':
                print "|    "*num  + "|-"+ node.nodeName.strip() + " ("+ getTagText(root,node.nodeName.strip()).strip() +")"
            else:
                print "|    "*num  + "|-"+ node.nodeName.strip()
            toStr(node,num+1)

dom = xml.dom.minidom.parseString(test.strip())
root = dom.documentElement

toStr(root,0) 

Tags: Python


Monday, April 19, 2010

统计文件夹下Java源代码行数的python代码

import sys;
import os;

class LineCount:
    def trim(self, docstring):
        if not docstring:
            return ''
        lines = docstring.expandtabs().splitlines()
        
        indent = sys.maxint
        for line in lines[1:]:
            stripped = line.lstrip()
            if stripped:
                indent = min(indent, len(line) - len(stripped))
        
        trimmed = [lines[0].strip()]
        if indent < sys.maxint:
            for line in lines[1:]:
                trimmed.append(line[indent:].rstrip())
        
        while trimmed and not trimmed[-1]:
            trimmed.pop()
        while trimmed and not trimmed[0]:
            trimmed.pop(0)
        
        return '\n'.join(trimmed)
    
    def FileLineCount(self, filename):
        (filepath,tempfilename) = os.path.split(filename);
        (shotname,extension) = os.path.splitext(tempfilename);
        if extension == '.java':                            # file type
            file = open(filename,'r');
            self.sourceFileCount += 1;
            allLines = file.readlines();
            file.close();
                
            lineCount    = 0;
            commentCount = 0;
            blankCount   = 0;
            codeCount    = 0;
            for eachLine in allLines:
                if eachLine != " " :
                    eachLine = eachLine.replace(" ", "");       # remove space
                    eachLine = self.trim(eachLine);             # remove tabIndent
                    if (eachLine.startswith("//")       == 1
                        or eachLine.startswith("*")     == 1
                        or eachLine.startswith("/*")    == 1
                        or eachLine.startswith("*/")    == 1):  # LINECOMMENT
                        commentCount += 1;
                    else :
                        if eachLine == "":
                            blankCount += 1;
                        else :
                            codeCount += 1;
                lineCount = lineCount + 1;
            self.all        += lineCount;
            self.allComment += commentCount;
            self.allBlank   += blankCount;
            self.allSource  += codeCount;
            print filename;
            print '           Total      :',lineCount;
            print '           Comment    :',commentCount;
            print '           Blank      :',blankCount;
            print '           Source     :',codeCount;                        

    def CalulateCodeCount(self,filename):
        if os.path.isdir(filename) :
            if not filename.endswith('\\'):
                filename += '\\';
            for file in os.listdir(filename):
                if os.path.isdir(filename + file):
                    self.CalulateCodeCount(filename + file);
                else:
                    self.FileLineCount(filename + file);
        else:
            self.FileLineCount(filename);

    # Open File
    def __init__(self):
        self.all            = 0;
        self.allComment     = 0;
        self.allBlank       = 0;
        self.allSource      = 0;
        self.sourceFileCount= 0;
        filename = raw_input('Enter File Folder Path : ');
        self.CalulateCodeCount(filename);
        if self.sourceFileCount == 0 :
            print 'No Code File';
            pass;
        print '\n';
        print '*****************  All Files  **********************';
        print '    Files      :',self.sourceFileCount;
        print '    Total      :',self.all;
        print '    Comment    :',self.allComment;
        print '    Blank      :',self.allBlank;
        print '    Source     :',self.allSource;
        print '****************************************************';

myLineCount = LineCount(); 

Tags: Python, Java


Tuesday, October 14, 2008

分别用javascript和Python处理相同的字符串

http://www.popub.net/script/pcasunzip.html有一个省、市、地区联动选择JS封装类
javascript是这样实现的:将所有省市区的名字放到一个字符串里使用分隔符分割,
这个字符串很长,在点击 这里下载javascript的实现。
下面的javascrip将省市区分别放在PCAPPCACPCAA三个数组里:

PCAD="北京市$市辖..."//太长省略
PCAArea=[];
PCAP=[];//All Provinces
PCAC=[];//All Cities   PCAC[ProvinceIndex][i];
PCAA=[];//All Areas   PCAA[ProvinceIndex][CityIndex][i]

PCAN=PCAD.split("#");
alert("province Length:   "+PCAN.length)
for(i=0;i<PCAN.length;i++)
{
    
PCAA[i]=[];TArea=PCAN[i].split("$")[1].split("|");
    
for(j=0;j<TArea.length;j++)
    {
        
PCAA[i][j]=TArea[j].split(",");
        
if(PCAA[i][j].length==1)
            
PCAA[i][j][1]=SAT;
        
TArea[j]=TArea[j].split(",")[0]
    }
    
PCAArea[i]=PCAN[i].split("$")[0]+","+TArea.join(",");
    
PCAP[i]=PCAArea[i].split(",")[0];
    
PCAC[i]=PCAArea[i].split(',')
}


下面我用Python处理上面相同的字符串取出所有省市区:

# coding=utf-8

 

import string

 

SPT="请选择省份"

SCT="请选择城市"

SAT="请选择地区"

PCAD="北京市$市辖区,东城区,西…"; #太长省略

PCAD=SPT+"$"+SCT+","+SAT+"#"+PCAD

PCAArea=[]

PCAP=[]#fAll Provinces

PCAC=[]#fAll Cities   PCAC[ProvinceIndex][i];

PCAA=[]#fAll Areas   PCAA[ProvinceIndex][CityIndex][i]

PCAN=PCAD.split("#")

 

for PCAN_I in PCAN:

    lst = []# PCAA[i]

    TArea=PCAN_I.split("$")[1].split("|")

    for TArea_J in TArea:

        PCAA_I_J=TArea_J.split(",")

        if(len(PCAA_I_J)==1):

            PCAA_I_J.append(SAT)

        lst.append(PCAA_I_J)# PCAA[i][j]

        TArea_J=TArea_J.split(",")[0]

    PCAA.append(lst)

    PCAArea_I = PCAN_I.split("$")[0]+","+string.join(TArea,',')

    PCAArea.append(PCAArea_I)

    PCAP.append(PCAArea_I.split(",")[0])

    PCAC.append(PCAArea_I.split(','))

 

for pid in range(len(PCAP)):

    for cid in range(len(PCAA[pid])):

        for aid in range(len(PCAA[pid][cid])):

            if(aid!=0):

                print PCAP[pid] +"\t"+ PCAA[pid][cid][0] +"\t"+ PCAA[pid][cid][aid]

 


Tags: Python