1. 程式人生 > 實用技巧 >5章程式碼

5章程式碼

5.3 獲得漢字長度和分解

#coding=utf8
import arcpy

import os
import sys
import math
import string
from collections import namedtuple

#判斷字串是否為漢字
def isChineseWord(string):
    if string.isalpha():
        if ord(string) in range(65,91) or ord(string) in range(97,123) :
            print("是字母")
            return
False else: print("是漢字") return True print("不是漢字也不是字母") return False #返回漢字和英文數量 def getChinesenum(s): s_len = len(s) cnum=0 for c in s: if isChineseWord(c): cnum+=1 return cnum,s_len-cnum def str_count(s): '''找出字串中的中英文、空格、數字、標點符號個數
''' count_en = count_dg = count_sp = count_zh = count_pu = 0 s_len = len(s) for c in s: if c in string.ascii_letters: #英文 count_en += 1 elif c.isdigit(): #數字 count_dg += 1 elif c.isspace(): #空格 count_sp += 1 elif c.isalpha(): #
方法檢測字串是否只由字母組成。 count_zh += 1 else: count_pu += 1 #標點 total_chars = count_zh + count_en + count_sp + count_dg + count_pu if total_chars == s_len: return namedtuple('Count', ['total', 'zh', 'en', 'space', 'digit', 'punc'])(s_len, count_zh, count_en, count_sp, count_dg, count_pu) else: print('Something is wrong!') return None return None #漢字長度 def getcharlength(mystr): #在u下一個漢字長度為3 lenTxt = len(mystr) lenTxt_utf8 = len(mystr.decode('utf-8')) size = int((lenTxt_utf8 - lenTxt)/2 + lenTxt) return size #如果返回為None,就是沒有返回值 def getlength(): ss="我們的gis" num=len(ss) arcpy.AddMessage(u"{1} length={0}".format(num,ss)) #u加不加都一樣 一個漢字為3 arcpy.AddMessage("{1} length={0}".format(num,ss)) ss=u"我們的gis" #加u,一個漢字為1 num=len(ss) arcpy.AddMessage(u"ss={1} length={0}".format(num,ss)) arcpy.AddMessage("ss={1} length={0}".format(num,ss)) ss=u"我們的gis" #加u,一個漢字為1 num=getcharlength(ss) arcpy.AddMessage("{1} length={0}".format(num,ss)) ss="我們的gis" #不加u,一個漢字為2 num=getcharlength(ss) arcpy.AddMessage("{1} length={0}".format(num,ss)) s = u'我們的gis gisoracle 2019.11.07' #一定要加u count = str_count(s) arcpy.AddMessage(s) arcpy.AddMessage('該字串共有 {} 個字元,其中有 {} 個漢字,{} 個英文,{} 個空格,{} 個數字,{} 個標點符號。'.format(count.total, count.zh, count.en, count.space, count.digit, count.punc)) cnum,enum=getChinesenum(s) arcpy.AddMessage('該字串共有 {} 漢字字元,非漢字{}'.format(cnum,enum)) s=u"我們的gis" arcpy.AddMessage('該字串 {} 取左邊4個{}'.format(s,s[0:4])) s="我們的gis" #下面沒有取出來,一定加u arcpy.AddMessage('該字串 {} 取左邊4個{}'.format(s,s[0:4])) def printinfo(): #不能名稱為print arcpy.AddMessage("====================我們都是Python程式設計師=============") arcpy.AddMessage(u"====================我們都是Python程式設計師=============") #加不加都一樣 arcpy.AddMessage("{0:<20s}1".format(u"我們都是程式設計師")) arcpy.AddMessage("{0:<20s}12345678901234567890".format("我們都是程式設計師")) #需要加u arcpy.AddMessage("%-20s12345678901234567890"%(u"我們都是程式設計師")) arcpy.AddMessage("%-20s12345678901234567890"%("我們都是程式設計師")) #需要加u arcpy.AddMessage(u"沒有對應資料".encode('gbk')) # 漢字亂碼的解決 #把字串按漢字固定2為擷取 def gettrim(s,n): num=0 first="" after="" for c in s: if isChineseWord(c): num+=2 #漢字2位 else: num+=1 #其他1位 if num<=n: first=first+c else: after=after+c return first,after def strtrim(): s=u"我們1的gis1" first,after=gettrim(s,6) arcpy.AddMessage('{} 取6位,前{} 後{}'.format(s,first,after)) s="我們1的gis1" #不加u,一個漢字3位 first,after=gettrim(s,6) arcpy.AddMessage('{} 取6位,前{} 後{}'.format(s,first,after)) def Main(): getlength() strtrim() printinfo() Main()

5.4 表中讀寫漢字

#coding=utf8
import arcpy
import os
import sys
import math
def readHZ():
    fields = [inField]
    with arcpy.da.SearchCursor(inTable, fields) as cursor:
        i=1
        for row in cursor:
            arcpy.AddMessage(u"序號{0}, 欄位={1}, 值={2}".format(i,inField,row[0]))
            i=i+1

def updateHZ():
    fields = [inField]
    with arcpy.da.UpdateCursor(inTable, fields) as cursor:
        i=1
        for row in cursor:
            #mystr=row[0]+u" 長度"+str(i)
            mystr=row[0]+" 長度"+str(i) #加u,不加u都可以
            mystr=mystr[0:50]
            row[0]=mystr
            cursor.updateRow(row)
            i=i+1
def insertHZ():
    fields = (inField)
    cursor = arcpy.da.InsertCursor(inTable, fields)
    for x in xrange(0, 2):
        #cursor.insertRow((str(x*100)+u"我愛你",)) #最後必須加,可以不加u 加u和不加u一樣
        cursor.insertRow((str(x*100)+"我愛你",))
    del cursor
def main():
    readHZ()
    updateHZ()
    insertHZ()

inTable=arcpy.GetParameterAsText(0)
inField=arcpy.GetParameterAsText(1)
main()

5.5 讀寫文字檔案中漢字

#coding=utf8
import arcpy

import os
import sys
import math
import codecs
def ReadTXTNEW(txtFile):
    f = codecs.open(txtFile,'r','gbk') #'utf-8'

    lines = f.readlines()
    f.close()
    return lines

def ReadTXT(txtFile):

    f = open(txtFile)
    mystr= f.read()
    f.close()
    return mystr

#返回陣列
def ReadTXTList(txtFile):
    sumlist=[]
    f = open(txtFile,"r") #
    try:
        lines = f.readlines()
        for line in lines:
            curline=line.replace('\n', '') #刪除\n
            sumlist.append(curline)
    finally:
        f.close()
    return sumlist

def WriteTXT(mylist,txtFile):
    wfiles = open(txtFile,'w')
    num=len(mylist)

    try:
        for i in range(num):
            wfiles.write(mylist[i]+'\n')
    finally:
        wfiles.close()
    if wfiles:
        del wfiles

def main(inFile):
    pList=ReadTXTList(inFile)
    num=len(pList)
    for i in range(num):
        arcpy.AddMessage("{0}={1}".format(i,pList[i]))
        #arcpy.AddMessage("u{0}={1}".format(i,pList[i])) #這裡不需要加u,加u出錯誤,因為沒有漢字
    txtFile=inFile.lower().replace('.txt', '1.txt')
    mystr=u"我愛你 gisoracle"
    pList.append(mystr.encode("GBK")) ##解決中文亂碼問題,直接pList.append(mystr)出來亂碼
    #pList.append(mystr) #錯誤
    WriteTXT(pList,txtFile)
inFile=arcpy.GetParameterAsText(0)
main(inFile)

5.6 元組和列表中漢字使用

#coding=utf8
import arcpy

import os
import sys
import math

##將列表轉換為元組。
def usetuple():
    tup1 = ('我愛你 qq', '我愛你 gisorcle', 2019, 2000) #不要加u,否則後面亂碼如 u'\u6211\u7231\u4f60 gisorcle'
    num=len(tup1)
    for i in range(num):
        arcpy.AddMessage("{0}={1}".format(i,tup1[i]))
    ss=str(tup1[2:4]) #從2,4,不包括4

    arcpy.AddMessage("{0}".format(ss))
    ss=str(tup1[0:1]) #從0,1,不包括1
    ss = ss.decode('string-escape')# 不加ss = ss.decode('string-escape') 輸出 \xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0
    arcpy.AddMessage("{0}".format(ss))

#列表
def useList():
    List = ['我愛你 qq', '我愛你 gisorcle'] #不要加u,否則後面亂碼入 u'\u6211\u7231\u4f60 gisorcle'
    List.append("我愛")
    num=len(List)
    for i in range(num):
        arcpy.AddMessage("{0}={1}".format(i,List[i]))
    ss=str(List[0:3]) #從0,3,不包括3
    ss = ss.decode('string-escape')# 不加ss = ss.decode('string-escape') 輸出 \xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0
    arcpy.AddMessage("{0}".format(ss))

def main():
    useList()
    usetuple()
main()

5.7 字典使用

#coding=utf8
import arcpy

import os
import sys
import math
def main():
    d = {}
    fields = arcpy.ListFields(inFeature)
    for field in fields:
        d[field.name] = field.aliasName
    for key in d.keys():
        arcpy.AddMessage("{0}={1}".format(key,d[key]))
    for item in d.items():
        ss = str(item).decode("unicode_escape")
        arcpy.AddMessage("===={0}".format(ss))

inFeature=arcpy.GetParameterAsText(0)
main()