用python實現(xiàn)英文字母和相應(yīng)序數(shù)轉(zhuǎn)換的方法
第一步:字母轉(zhuǎn)數(shù)字
英文字母轉(zhuǎn)對應(yīng)數(shù)字相對簡單,可以在命令行輸入一行需要轉(zhuǎn)換的英文字母,然后對每一個字母在整個字母表中匹配,并返回相應(yīng)的位數(shù),然后累加這些位數(shù)即可。過程中,為了使結(jié)果更有可讀性,輸出相鄰數(shù)字間怎加了空格,每個對應(yīng)原來單詞間增加逗號。
c="abcdefghijklmnopqrstuvwxyz"
temp=''
list=[]
s=input()
num=len(s)
list.append(s)
for i in range(0,num):
if list[0][i]==' ':
temp+=','
else:
for r in range(1,26):
if list[0][i]==c[int(r)-1]:
temp+=str(r)
temp+=' '
print("輸出結(jié)果為:%s"%temp)
第二步:數(shù)字轉(zhuǎn)字母
數(shù)字轉(zhuǎn)字母有個難點就是,當輸入一行數(shù)字,如何才能合理地把它們每個相應(yīng)位的數(shù)取出來。
才開始想到用正則匹配,定模式單元(\d+,{0,}),然后希望每個數(shù)字用.groups()形式返回一個元組(tuple),但限于要輸入數(shù)字的個數(shù)位置,沒找到好的匹配方式。
然后用到了split()函數(shù),用相應(yīng)的分隔符分割一段字符串之后,將值已list形式返回。
c="abcdefghijklmnopqrstuvwxyz"
temp=''
s=input()
s_list=s.split(",")
num=len(s_list)
for i in range(0,num):
if s_list[i]==' ':
temp+=' '
else:
result=c[int(s_list[i])-1]
temp+=result
print("輸出結(jié)果是:%s"%temp)
完整代碼
#-*- coding: utf-8 -*-
import re
def main():
ss=input("請選擇:\n1.字母->數(shù)字\
\n2.數(shù)字->字母\n")
if ss=='1':
print("請輸入字母: ")
fun1()
elif ss=='2':
print("請輸入數(shù)字:")
fun2()
def fun1():
c="abcdefghijklmnopqrstuvwxyz"
temp=''
list=[]
s=input()
num=len(s)
list.append(s)
for i in range(0,num):
if list[0][i]==' ':
temp+=','
else:
for r in range(1,26):
if list[0][i]==c[int(r)-1]:
temp+=str(r)
temp+=' '
print("輸出結(jié)果為:%s"%temp)
def fun2():
c="abcdefghijklmnopqrstuvwxyz"
temp=''
s=input()
s_list=s.split(",")
num=len(s_list)
for i in range(0,num):
if s_list[i]==' ':
temp+=' '
else:
result=c[int(s_list[i])-1]
temp+=result
print("輸出結(jié)果是:%s"%temp)
if __name__ == '__main__':
main()
便可利用該python代碼實現(xiàn)英文字母和對應(yīng)數(shù)字的相互轉(zhuǎn)換。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python英文文章詞頻統(tǒng)計(14份劍橋真題詞頻統(tǒng)計)
這篇文章主要介紹了Python英文文章詞頻統(tǒng)計(14份劍橋真題詞頻統(tǒng)計),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
詳解Python中sorted()和sort()的使用與區(qū)別
眾所周知,在Python中常用的排序函數(shù)為sorted()和sort()。本文將詳細介紹sorted()和sort()方法的代碼示例,并解釋兩者之間的區(qū)別,感興趣的可以了解一下2022-03-03

