Python中文轉數字(整數,小數,純數字通用版)

2021-08-31 11:33:57 字數 3138 閱讀 5630

chinese_number_dict =

not_in_decimal =

"十百千萬億點"

defch2num

(chstr):if

'點'not

in chstr:

return ch2round(chstr)

splits = chstr.split(

"點")

iflen

(splits)!=2

:return splits

rount = ch2round(splits[0]

) decimal = ch2decimal(splits[-1

])if rount is

notnone

and decimal is

notnone

:return

float

(str

(rount)

+"."

+str

(decimal)

)else

:return

none

defch2round

(chstr)

: no_op =

true

iflen

(chstr)

>=2:

for i in chstr:

if i in not_in_decimal:

no_op =

false

else

: no_op =

false

if no_op:

return ch2decimal(chstr)

result =

0 now_base =

1 big_base =

1 big_big_base =

1 base_set =

set(

) chstr = chstr[::

-1]for i in chstr:

if i not

in chinese_number_dict:

return

none

if chinese_number_dict[i]

>=10:

if chinese_number_dict[i]

> now_base:

now_base = chinese_number_dict[i]

elif now_base >= chinese_number_dict[

"萬"]

and now_base < chinese_number_dict[

"億"]

and chinese_number_dict[i]

> big_base:

now_base = chinese_number_dict[i]

* chinese_number_dict[

"萬"]

big_base = chinese_number_dict[i]

elif now_base >= chinese_number_dict[

"億"]

and chinese_number_dict[i]

> big_big_base:

now_base = chinese_number_dict[i]

* chinese_number_dict[

"億"]

big_big_base = chinese_number_dict[i]

else

:return

none

else

:if now_base in base_set and chinese_number_dict[i]!=0

:return

none

result = result + now_base * chinese_number_dict[i]

base_set.add(now_base)

if now_base not

in base_set:

result = result + now_base *

1return result

defch2decimal

(chstr)

: result =

""for i in chstr:

if i in not_in_decimal:

return

none

if i not

in chinese_number_dict:

return

none

result = result +

str(chinese_number_dict[i]

)return

int(result)

if __name__ ==

"__main__"

:print

(ch2num(

"一萬三千零二十"))

print

(ch2num(

"一萬三千兩百二十"))

print

(ch2num(

"兩百五十三"))

print

(ch2num(

"三十二"))

print

(ch2num(

"二")

)print

(ch2num(

"二二三五七"))

print

(ch2num(

"十")

)print

(ch2num(

"百")

)print

(ch2num(

"十二點五"))

print

(ch2num(

"三點一四一五九二六"))

print

(ch2num(

"三千五百億一千三百二十五萬四千五百六十九點五八三四三九二九一"

))

output:

13020

13220

25332

222357

10100

12.5

3.1415926

350013254569.58344

Python 旋轉陣列的最小數字

把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個非遞減排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。例如陣列為的乙個旋轉,該陣列的最小值為1。note 給出的所有元素都大於0,若陣列大小為0,請返回0。coding utf 8 旋轉陣列的最小數字 題目描述 把乙個陣列最開始...

8旋轉陣列最小數字PYTHON

把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個非遞減排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。例如陣列為的乙個旋轉,該陣列的最小值為1。note 給出的所有元素都大於0,若陣列大小為0,請返回0。思路 使用二分查詢 1 設定乙個首部指標low,乙個尾部指標high,以...

旋轉陣列的最小數字 python

原始碼 把乙個陣列最開始的若干個元素搬到陣列的末尾,我們稱之為陣列的旋轉。輸入乙個非減排序的陣列的乙個旋轉,輸出旋轉陣列的最小元素。例如陣列為的乙個旋轉,該陣列的最小值為1。note 給出的所有元素都大於0,若陣列大小為0,請返回0。思路 劍指offer中有這道題目的分析。這是一道二分查詢的變形的題...