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

时间:2014-10-23 07:04:28

标签: python converter phone-number letter

我正在尝试完成将字母转换为电话号码序列的代码。我需要的是将例如JeromeB改为537-6632。此外,我需要程序在最后一个可能的数字后切断字母翻译。所以例如在1-800-JeromeB之后,即使我在1-800-JeromeBrigham写作,它也不会编码。但问题是我不明白如何将其隐含到我的代码中。我不明白要切断最后一封信并放入仪表板。我现在拥有的是这个

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  

5 个答案:

答案 0 :(得分:1)

# 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'}

更新:切断第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

已更新:输入"结束"终止

# 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)))

输入:JeromeBrigham

输出:5376-632

答案 1 :(得分:0)

如果您想要始终输出7个字符(否则会引发错误),您应该使用固定的range(7)而不是range(len(phone))

对于短划线,只需检查当前索引。如果是3,请添加破折号。

答案 2 :(得分:0)

尝试使用包含alphas作为键的字典和相应的数字作为值,然后只迭代前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

您还可以获取输入的子字符串

number[:10]

答案 3 :(得分:0)

只是使用固定长度,这不是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"])

答案 4 :(得分:0)

string.maketrans函数生成1:1转换映射,并在字符串上调用translate并传递此映射将一步转换字符串。例如:

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]

输出:

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