用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设计】。

相关文章

python-Web-flask-视图内容和模板知识点西宁街

基本使用 #设置cookie值 @app.route('/set_cookie') def set_cookie(): response = make_response("...

python解压TAR文件至指定文件夹的实例

如下所示: ######### Extract all files from src_dir to des_dir def extract_tar_files(src_dir,des...

解决Pytorch训练过程中loss不下降的问题

在使用Pytorch进行神经网络训练时,有时会遇到训练学习率不下降的问题。出现这种问题的可能原因有很多,包括学习率过小,数据没有进行Normalization等。不过除了这些常规的原因,...

使用Python中的greenlet包实现并发编程的入门教程

1   动机 greenlet 包是 Stackless 的副产品,其将微线程称为 “tasklet” 。tasklet运行在伪并发中,使用channel进行同步数据...

pycharm 使用心得(七)一些实用功能介绍

pycharm 使用心得(七)一些实用功能介绍

实时比较 PyCharm 对一个文件里你做的改动保持实时的跟踪,通过在编辑器的左侧栏显示一个蓝色的标记。这一点非常方便,我之前一直是在Eclipse里面用命令“Compare again...