1

我是 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 做到这一点。

4

2 回答 2

0
  1. 仅将您的密钥转换为文本,这样16就变成了'16'

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

  3. 看起来需要一个贪心算法。您需要查看代码“数字”的最大长度,并检查该长度的移动窗口;如果这不匹配任何内容,则在您的列表中搜索较小的一个,依此类推,直到您错过。当您点击时,输出找到的字母,然后在匹配的文本(数字)之后开始前进到一个新窗口。


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

这依赖于按密钥长度排序来获得更长匹配的特权。

于 2013-09-19T16:12:43.827 回答
-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将保留结果。

于 2013-09-19T16:25:38.477 回答