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

标签 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 执行此操作。

最佳答案

  1. 将您的 key 仅转换为文本,以便 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')

这依赖于按 key 长度排序以优先进行较长的匹配。

关于algorithm - 如何在python中将数字转换为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18899756/

相关文章:

algorithm - 为什么 MQTT 对剩余长度使用如此奇怪的编码方案?

c++ - 一组线性点的高效最长算术级数

c++ - 发现两个字符串是循环的

python - 当 A、B、M 是大数时,如何计算 (A^B)%M?

algorithm - 找到 x^2+y^2=z^2 解决方案的最佳复杂度

java - 如何加载包含变音符号的文件名的资源 JAR?

algorithm - 如何构建知识图谱?

javascript - 你什么时候应该使用转义而不是 encodeURI/encodeURIComponent?

c# - 如何将 UTF-8 阿拉伯字母转换为 CodePage 1001?

encoding - 带替换的 Blob.decode 似乎不起作用