如何在dict中将字母转换为数字

时间:2017-05-26 00:15:08

标签: python

def get_phone_number(word_str):
    numpad_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, 't': 8, 'u': 8, 'v': 8, 'w': 9, 'x': 9, 'y': 9, 'z': 9}
    number = '0800painter'
    re_text = ''
    for digit in number:
        re_text += str(numpad_dict.get(digit, digit))
    return re_text


def test_get_phone_number():
    print(get_phone_number('0800painter'))
    print(get_phone_number('0800fixnow'))

def main():
    print("===========\nQuestion 1:")
    test_get_phone_number()
main()

输出:

===========
Question 1:
08007246837
08007246837

我从我的第一个def功能,如何根据' 0800fixnow'得到第二个答案得到了一个答案?我是否需要编写两个for循环来获得答案或只需一个?

2 个答案:

答案 0 :(得分:0)

您正在 private void setUpTimeline() { double offset = displayWidth + 20; // starting x-pos for message stream double playtime = 0; Queue<Message> messageBuffer = feeder.filterNewsBuffer(filteredTopics); while (!messageBuffer.isEmpty()) { Map<String,Color> colorMap = setColorMap(); Timeline timeline = new Timeline(); Message latestMessage; //THE PRINT System.out.println(messageBuffer.peek()); latestMessage = messageBuffer.poll(); Message.Status status = latestMessage.status; Message.Topic topic = latestMessage.topic; String messageBody = latestMessage.text + " " + "\uD83D\uDE40"; Text text = new Text(offset, displayHeight - 15, messageBody); text.setFont(Font.font("Tahoma", FontWeight.BLACK, 80)); text.setTextOrigin(VPos.BASELINE); text.setFill(colorMap.get(topic.toString())); double mesWidth = text.getLayoutBounds().getWidth(); playtime += mesWidth / playSpeed; setNewsPieceForRun(text, group, timeline, playtime); offset += mesWidth; } } 函数中定义数字,而不是使用函数参数中提供的数字。将功能更改为

get_phone_number

应该解决您的问题。

答案 1 :(得分:0)

numpad_dict = {
  2: "abc",
  3: "def",
  4: "ghi",
  5: "jkl",
  6: "mno",
  7: "pqrs",
  8: "tuv",
  9: "wxyz"
}

def letter_to_number(phone_number):
  output = ""
  for character in phone_number:
    try:
      int(character)
      output += character
    except ValueError:
      for key in numpad_dict:
        if character in numpad_dict[key]:
          output += str(key)
          break
  return output

print(letter_to_number('0800painter'))
print(letter_to_number('0800fixnow'))

# returns

08007246837
0800349669