【问题标题】:Python 2.7 Convert Letters to Phone NumbersPython 2.7 将字母转换为电话号码
【发布时间】:2014-12-18 19:29:33
【问题描述】:

我正在尝试完成将字母转换为电话号码序列的代码。我需要做的是例如 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  

【问题讨论】:

  • 尝试使用字典。我太困了,无法测试我的答案。但是您可以使用字典轻松完成此操作。但是,当您特别要求输入“xxx-xxx-xxxx”时,为什么要输入“1-800-JeromeBrigham”?
  • 你说得对,我也困了哈哈哈。谢谢你

标签: python converter phone-number letter


【解决方案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

更新:输入“end”表示终止

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

输入:杰罗姆布里格姆

输出:5376-632

【讨论】:

  • 谢谢你的作品。是否有任何程序可以在不提示用户这样做的情况下自行输入破折号。就像用户输入 NYGBEST 一样,它会是 xxx-xxxx。
  • 我正在尝试删除要求用户以 xxx-xxx-xxxx 格式输入数字的提示。我希望代码为用户添加破折号,其他一切都很完美。
  • 那至少我们可以限制用户输入的字符数?
  • @d-coder 好的,所以让我们将其限制为 10。我们如何制作代码输入破折号。如果用户输入 JeromeB,它只会插入 xxx-xxxx。
  • @Andrew 所以你想要这个? 输入:1-800-JeromeBrigham 输出:1-800-537-6632
【解决方案2】:

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

至于破折号,只需检查当前索引即可。如果是 3,请添加破折号。

【讨论】:

  • 有什么办法可以让我把它剪掉,字母不重要而不是错误。另外我将如何更改当前索引?
【解决方案3】:

尝试使用以字母作为键,将相应数字作为值的字典,然后只迭代前 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]

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 所以我只需要替换我的变量并添加这个?
    • 因为我不懂
    【解决方案5】:

    有一个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
    

    【讨论】:

    • 当我测试这个时,我仍然得到额外的数字。因为我在询问 xxx-xxx-xxxx 格式时犯了一个错误。有没有一种方法可以在代码中加入自动破折号而不要求用户自己输入。
    • 你是怎么得到多余的数字的?它在 12 处截断,并且需要两个连字符,因此应始终为 10 位。
    • 您可以只要求输入长度为 10 或更长,并使用 print '{}-{}-{}'.format(phone[:3],phone[3:6],phone[6:10]) 自己添加连字符。
    • 当我输入代码时,我对其进行了测试,但由于某种原因截断不起作用。