作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我是 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 执行此操作。
最佳答案
将您的 key 仅转换为文本,以便 16
变为 '16'
将其存储在将“数字”映射到代码字母的映射中。
看起来需要一个贪心算法。您需要查看代码“数字”的最大长度,并检查该长度的移动窗口;如果那不匹配,则在列表中搜索一个较小的,依此类推,直到您错过为止。当你命中时,输出找到的字母,并前进到一个新窗口,从匹配的文本(数字)之后开始。
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/
我是一名优秀的程序员,十分优秀!