微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何根据字母映射将输入的数字字符串转换为句子? 问题解决方案改进

如何解决如何根据字母映射将输入的数字字符串转换为句子? 问题解决方案改进

我正在尝试编写一个简单的函数,将数字字符串转换为相应的句子。每个数字代表一个字母(1=A,2=B...26=Z)。句子中的单词用“+”分隔,字母用空格分隔。例如,输入 num_to_letters('20 5 19 20+4 15 13 5') 应返回 'TEST DOME'。

import string

def num_to_letters(s):
  '''Converts input number string to a sentence'''

  alphabet = string.ascii_lowercase
  alphabet=[i for i in alphabet]
  dic = {i:j for i,j in enumerate(alphabet,1)}
  res = ''
  for num in s:
    if num in dic:
      res+= dic[int(num)]
    elif num == ' ':
      res+= ''     
    elif num == '+':
      res+= ' '
  return res

num_to_letters('8 9+13 9 8 9 18')

但是,我在输出中得到一个空字符串。这里有什么问题?

解决方法

问题

  1. 如果您逐个字符地迭代,您将无法一次读取多位数字 20。您可能需要 split 才能一一获取不同的元素。

    首先在 plus 符号周围放置空格,然后是 split(默认为空格)

    "8 9+13 9 8 9 18"  ==>  ['8','9','+','13','8','18']
    "20 5 19 20+4 15 13 5"  ==>   ['20','5','19','20','4','15','5']
    
  2. 你的 dict 的键是 ints 并且你从输入中读取 strings,所以你永远不会在你可能做的 dict 中找到键

    {str(i): j for i,j in enumerate(string.ascii_lowercase,1)}
    

解决方案

然后你的方法,经过一些简化,完成工作:

def num_to_letters(s):
    dic = {str(i): j for i,1)}
    values = s.replace("+"," + ").split()
    res = ''
    for num in values:
        if num in dic:
            res += dic[num]
        elif num == '+':
            res += ' '
    return res

改进

由于键是 ints 表示,您可以直接使用它们来索引字母 string.ascii_lowercase[int(num) - 1]

def num_to_letters(s):
    values = s.replace("+"," + ").split()
    return "".join(' ' if num == '+' else string.ascii_lowercase[int(num) - 1] for num in values)
,

这是一种使用 ASCII 的简单方法::

def num_to_letters(s):
  result = ""
  words = s.split("+")
  for word in words:
    letters = word.split(" ")
    for letter in letters:
      result = result + chr(int(letter) + 64)
    result = result + " "
  return result

print(num_to_letters("8 9+13 9 8 9 18"))
,

又快又脏:

import string

def num_to_letters(s):
    '''Converts input number string to a sentence'''
    list_num = s.split()
    num=[]
    for elm in list_num:
        if '+' in elm:
            a=elm.split('+')
            num.append(elm.split('+')[0])
            num.append('+')
            num.append(elm.split('+')[1])
        else:
            num.append(elm)

    alphabet = string.ascii_lowercase
    alphabet=[i for i in alphabet]
    dic = {i:j for i,j in enumerate(alphabet,1)}
    res = []
    for elm in num:
        if elm == '+':
            res.append(' ')
        else:
            res.append(dic[int(elm)])

    str1=''
    for ele in res:  
        str1 += ele
    print(str1.upper())
    res=str1.upper()
    return res

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。