用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编程实现希尔排序

python编程实现希尔排序

观察一下”插入排序“:其实不难发现她有个缺点:   如果当数据是”5, 4, 3, 2, 1“的时候,此时我们将“无序块”中的记录插入到“有序块”时,估计俺们要崩盘,每次插入都要移动位置...

Python随手笔记之标准类型内建函数

Python提供了一些内建函数用于基本对象类型:cmp(),repr(),str(),type()和等同于repr()的(' ')操作符 (1)type()    t...

Python实现删除时保留特定文件夹和文件的示例

实现功能:删除当前目录下,除保留目录和文件外的所有文件和目录 #!bin/env python import os import os.path import shutil def...

python tkinter实现界面切换的示例代码

python tkinter实现界面切换的示例代码

跳转实现思路 主程序相当于桌子: import tkinter as tk root = tk.Tk() 而不同的Frame相当于不同的桌布: face1 = tk....

python进程管理工具supervisor使用实例

python进程管理工具supervisor使用实例

平时我们写个脚本,要放到后台执行去,我们怎么做呢? 复制代码 代码如下: nohup python example.py 2>&1 /dev/null & 用tumx或者scre...