1

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

5 回答 5

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

输入:杰罗姆布里格姆

输出:5376-632

于 2014-10-23T07:48:48.583 回答
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
于 2014-10-23T07:28:27.170 回答
0

尝试使用带有字母作为键和相应数字作为值的字典,然后只迭代前 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]
于 2014-10-23T07:17:59.107 回答
0

如果要始终输出 7 个字符(否则会引发错误),则应使用 fixedrange(7)而不是。range(len(phone))

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

于 2014-10-23T07:10:13.663 回答
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"])
于 2014-10-23T07:23:38.717 回答