如何在python中将数字转换为文本

时间:2013-09-19 16:08:07

标签: algorithm encoding

我是Python新手并编写脚本/程序。

我想将数字转换为文字。 问题是数字没有任何分隔。

11349 - > TEI

16342734410 - > FEUERS

哪个数字必须是哪个字母已定义:

A = 6 B = 12 C = 15 D = 5 E = 34 F = 16 G = 8 H = 23 I = 9 J = 20 K = 33 L = 22 M = 17 N = 28 O = 19 P = 30 Q = 7 R = 4 S = 10 T = 11 U = 27 V = 13 W = 31 X = 14 Y = 29 Z = 35ß=18Ö= 32Ü=24Ä= 25

粗体部分存在问题,因为16可以读作1和6。

数字1,2和3未在我的列表中定义,必须与下一个数字一起阅读。

现在我需要一种简单的方法来让python执行此操作。

2 个答案:

答案 0 :(得分:0)

  1. 仅将您的密钥转换为文字,以便16变为'16'

  2. 将其存储在将“数字”映射到代码字母的地图中。

  3. 看起来像是一种贪婪的算法。您需要查看代码“number”的最大长度,并检查该长度的移动窗口;如果这与任何东西都不匹配,那么在列表中搜索一个较小的,依此类推,直到你错过。点击后,输出找到的字母,然后从匹配文本(数字)后面的新窗口前进。


  4. tablestr = '''A=6 B=12 C=15 D=5 E=34 F=16 G=8 H=23 I=9 J=20 K=33 L=22 M=17 N=28 O=19 P=30 Q=7 R=4 S=10 T=11 U=27 V=13 W=31 X=14 Y=29 Z=35 ß=18 Ö=32 Ü=24 Ä=25'''
    translationtable = dict((k,v) for v,k in (pair.split('=') for pair in tablestr.split(' ')))
    windowlen=2
    def decodergen(codetext):
        windowstart = 0
        windowend = windowlen
        # stop when we get to the end of the input
        while windowend <= len(codetext):
           #reduce window until len 1 
           while windowend - windowstart >= 1:
              key = codetext[windowstart:windowend]
              #print key
              if key in translationtable:
                 #setup new window
                 windowstart = windowend
                 windowend = windowstart + windowlen 
                 yield translationtable[key]
                 break # out of inner loop
              else:
                 windowend -=1     
           if windowend - windowstart <= 0:
              raise ValueError('Could not locate translation for code input')
    
    ''.join(decodergen('16342734410')) #=> 'FEUERS'
    

    这是一个更短的实现:

    import re
    rx = re.compile('|'.join(sorted(translationtable, key=len, reverse=True)))
    print rx.sub(lambda m: translationtable[m.group()], '16342734410')
    

    这取决于按键的长度排序以获得更长匹配的权限。

答案 1 :(得分:-1)

首先制作一本字典:

d = { '6' : "A",
      # etc
    }   

将数字转换为字符串:

code = str(my_num)

然后解析它:

t = ""
res = ""
for i in code:
    t += i
    if t in d.keys():
        res += d[t]
        t = ""

变量res会保留结果。