[閒聊] Mushclient中文數字轉阿拉伯數字Python版

看板mud_jy (金庸修真錄)作者 (rsliang)時間9年前 (2015/09/18 02:22), 9年前編輯推噓0(001)
留言1則, 1人參與, 最新討論串1/1
這個是剛好看到Mushclient有支援Python的script,閒閒無事拿來玩玩看的成果, 理論上是沒有bug啦,有的話請和我說,我再修修看,目前還是弱弱的Python新手。 說明: 一、__init__底下宣告的對應數字使用dict有更漂亮的寫法,剛開始寫的時候沒想 到,寫完了才想起來,所以就懶得改了。 二、純練Python用,很多地方的邏輯繞很多圈或是有多餘的宣告,請鞭小力一點:p =================================Code==================================== import os,sys class chs2num: def __init__(self): self.money = None self.total = 0 self.num = 0 self.hunmillion = 100000000 self.tenthousand = 10000 self.thousand = 1000 self.hundred = 100 self.ten = 10 self.one = 1 self.two = 2 self.three = 3 self.four = 4 self.five = 5 self.six = 6 self.seven = 7 self.eight = 8 self.nine = 9 self.zero = 0 self.curnum = 0 def tonum(self, money): self.money = money.decode('utf-8') for self.num in range(0, len(self.money)): world.Note(self.money[self.num]) if self.money[self.num] == u"一": self.curnum = self.one world.Note(self.curnum) elif self.money[self.num] == u"二" or (self.money[self.num] == u"兩" and self.num != (len(self.money) - 1)): self.curnum = self.two elif self.money[self.num] == u"三": self.curnum = self.three elif self.money[self.num] == u"四": self.curnum = self.four elif self.money[self.num] == u"五": self.curnum = self.five elif self.money[self.num] == u"六": self.curnum = self.six elif self.money[self.num] == u"七": self.curnum = self.seven elif self.money[self.num] == u"八": self.curnum = self.eight elif self.money[self.num] == u"九": self.curnum = self.nine elif self.money[self.num] == u"零": self.curnum = self.zero elif self.money[self.num] == u"十": if self.curnum == 0: self.total = self.total + self.ten else: self.total = self.total + self.curnum * self.ten self.curnum = 0 elif self.money[self.num] == u"百": self.total = self.total + self.curnum * self.hundred self.curnum = 0 elif self.money[self.num] == u"千": self.total = self.total + self.curnum * self.thousand self.curnum = 0 elif self.money[self.num] == u"萬": if self.curnum == 0: self.total = self.total * self.tenthousand else: self.total = (self.total + self.curnum) * self.tenthousand self.curnum = 0 elif self.money[self.num] == u"億": if self.curnum == 0: self.total = self.total * self.hunmillion else: self.total = (self.total + self.curnum) * self.hunmillion self.curnum = 0 if self.num == (len(self.money) - 1): if self.curnum < 10 and self.curnum > 0: self.total = self.total + self.curnum return self.total -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 112.104.181.23 ※ 文章網址: https://www.ptt.cc/bbs/mud_jy/M.1442514149.A.0BC.html

09/19 16:20, , 1F
你還可以增加一個"兩"的額外轉換
09/19 16:20, 1F
謝謝,已修改。 想法:語法上「兩」不會出現在個位數和十位數,因此十位數可以忽略,如果真的出現在 十位數前,亦可判別出來,至於個數位考慮字串誤抓單位的的可能,所以排除掉, 若真的也出現在個位數,那只要把and以及and之後的判斷式拿掉就好了。 ※ 編輯: rsliang (112.104.181.23), 09/21/2015 19:31:25
文章代碼(AID): #1L-mJb2y (mud_jy)
文章代碼(AID): #1L-mJb2y (mud_jy)