用python实现英文字母和相应序数转换的方法

yipeiwu_com6年前Python基础

第一步:字母转数字

英文字母转对应数字相对简单,可以在命令行输入一行需要转换的英文字母,然后对每一个字母在整个字母表中匹配,并返回相应的位数,然后累加这些位数即可。过程中,为了使结果更有可读性,输出相邻数字间怎加了空格,每个对应原来单词间增加逗号。

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("输出结果为:%s"%temp)

第二步:数字转字母

数字转字母有个难点就是,当输入一行数字,如何才能合理地把它们每个相应位的数取出来。

才开始想到用正则匹配,定模式单元(\d+,{0,}),然后希望每个数字用.groups()形式返回一个元组(tuple),但限于要输入数字的个数位置,没找到好的匹配方式。

然后用到了split()函数,用相应的分隔符分割一段字符串之后,将值已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("输出结果是:%s"%temp)

完整代码

#-*- coding: utf-8 -*-
import re
def main():
 ss=input("请选择:\n1.字母->数字\
    \n2.数字->字母\n")
 if ss=='1':
 print("请输入字母: ")
 fun1()
 elif ss=='2':
 print("请输入数字:")
 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("输出结果为:%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("输出结果是:%s"%temp)

if __name__ == '__main__':
 main()

便可利用该python代码实现英文字母和对应数字的相互转换。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django的models中on_delete参数详解

在Django2.0以上的版本中,创建外键和一对一关系必须定义on_delete参数,我们可以在其源码中看到相关信息 class ForeignKey(ForeignObject):...

python 画三维图像 曲面图和散点图的示例

用python画图很多是根据z=f(x,y)来画图的,本博文将三个对应的坐标点输入画图: 散点图: import matplotlib.pyplot as plt from mpl_...

在 Python 应用中使用 MongoDB的方法

在这篇文章中,将向您展示如何使用Python链接目前主流的MongoDB(V3.4.0)数据库,主要使用PyMongo(v3.4.0)和MongoEngine(V0.10.7)。同时比较...

Pyorch之numpy与torch之间相互转换方式

numpy中的ndarray转化成pytorch中的tensor : torch.from_numpy() pytorch中的tensor转化成numpy中的ndarray : nump...

浅谈Python的垃圾回收机制

一.垃圾回收机制 Python中的垃圾回收是以引用计数为主,分代收集为辅。引用计数的缺陷是循环引用的问题。 在Python中,如果一个对象的引用数为0,Python虚拟机就会回收这个对象...