简体   繁体   English

Python 2.7将字母转换为电话号码

[英]Python 2.7 Convert Letters to Phone Numbers

I am trying to complete a code that converts letters into a phone number sequence. 我正在尝试完成将字母转换为电话号码序列的代码。 What I need is to make for example JeromeB to 537-6632. 我需要的是将JeromeB制造为537-6632。 Also I need the program to cut off the letter translation after the last possible digit. 我还需要程序在最后一个可能的数字后切断字母翻译。 So for example after 1-800-JeromeB even if I write in 1-800-JeromeBrigham it will not code that. 因此,例如在1-800-JeromeB之后,即使我在1-800-JeromeBrigham中编写,它也不会编写该代码。 The thing is though I do not understand how to implicate that into my code. 问题是尽管我不明白如何将其隐含在我的代码中。 I do not know understand to cut off the last letter and put in the dash. 我不知道明白要剪掉最后一个字母然后加短划线。 What I currently have is this 我现在有这个

alph = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',\
        'q','r','s','t','u','v','w','x','y','z']
num =[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9]


phone = raw_input('enter phone number ').lower()

s = ""
for index in range(len(phone)):
    if phone[index].isalpha():
        s = s + str(num[alph.index(phone[index])])
    else:
        s = s + phone[index]
print s  
# define a dictionary
alph_num_dict = {'a': '2', 'b': '2', 'c': '2',\
                 'd': '3', 'e': '3', 'f': '3',\
                 'g': '4', 'h': '4', 'i': '4',\
                 'j': '5', 'k': '5', 'l': '5',\
                 'm': '6', 'n': '6', 'o': '6',\
                 'p': '7', 'q': '7', 'r': '7', 's': '7',\
                 'u': '8', 'w': '9', 'v': '8',\
                 'w': '9', 'x': '9', 'y': '9', 'z': '9'}

updated : Cut off chars which follow 7th char, and insert dash in the 4th place 已更新 :切掉第7个字符之后的字符,并在第4个位置插入破折号

# define a generator for converting string and cutting off it
def alph_to_num(phone):
    for index in range(len(phone)):
        if index >= 7:
            return

        if index == 4:
            yield '-'

        p = phone[index]

        if p in alph_num_dict:
            yield alph_num_dict[p]
        else:
            yield p

updated : Enter "end" for termination 更新 :输入“结束”以终止

# get input and join all converted char from generator
while True:
    phone = raw_input('enter phone number in the format xxxxxxx, or enter "end" for termination ').lower()

    if phone == 'end':
        break

    print ''.join(list(alph_to_num(phone)))

input : JeromeBrigham 输入 :JeromeBrigham

output : 5376-632 输出 :5376-632

You should use a fixed range(7) instead of range(len(phone)) if you want to always output 7 characters (and raise an error otherwise). 如果要始终输出7个字符(否则会引发错误),则应使用固定的range(7)而不是range(len(phone)) )。

As for the dashes, just check the current index. 至于破折号,只需检查当前索引。 If it's 3, add a dash. 如果是3,请添加破折号。

Try using a dictionary with alphas as keys and the corresponding numbers as values, then just iterate the first 10 indexes 尝试使用以字母为键,相应数字为值的字典,然后仅迭代前10个索引

phone = {'A' : 2, 'B' : 2, 'C' : 2, 'D' : 3, ....}

number = input("Enter a phone number")
counter = 1
for index in number:
  if counter < 10:
    print phone[number]
  counter += 1

You can also get a substring of the input 您还可以获取输入的子字符串

number[:10]

just use fixed length, and this is so not Pythonic, below is a more elegant rewrite 只是使用固定长度,所以不是Pythonic,下面是一个更优雅的重写

# please complete this map
phone_map = {'a':'2','b':'2','c':'2','d':'3','e':'3','f':'3'} 
"".join([ phone_map[digit] if digit.isalpha() else digit for digit in "abc123abc"])

There is a string.maketrans function that generates a 1:1 translation mapping, and calling translate on a string and passing this mapping will translate a string in one step. 有一个string.maketrans函数可生成1:1转换映射,对字符串调用translate并传递此映射将一步转换一个字符串。 Example: 例:

import string
import re

# This builds the 1:1 mapping.  The two strings must be the same length.
convert = string.maketrans(string.ascii_lowercase,'22233344455566677778889999')

# Ask for and validate a phone number that may contain numbers or letters.
# Allows for more than four final digits.
while True:
    phone = raw_input('Enter phone number in the format xxx-xxx-xxxx: ').lower()
    if re.match(r'(?i)[a-z0-9]{3}-[a-z0-9]{3}-[a-z0-9]{4,}',phone):
        break
    print 'invalid format, try again.'

# Perform the translation according to the conversion mapping.
phone = phone.translate(convert)

# print the translated string, but truncate.
print phone[:12]

Output: 输出:

Enter phone number in the format xxx-xxx-xxxx: 123-abc-defgHIJK
123-222-3334

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM