使用python将字母转换为数字

时间:2012-11-21 17:34:37

标签: python list dictionary decoding

我有什么:

s='areyo uanap ppple'

我想要的是什么:

s='12345 12324 11123'

我应该使用词典并翻译i中的每个s.split(' ')吗?还是有更简单的方法?

4 个答案:

答案 0 :(得分:2)

s='areyo uanap ppple'
incr=1
out=''
dict={}
for x in s:
    if ' ' in x:
        incr=1
        dict={}
        out+=' '
        continue;
    if x in dict.keys():
        out+=str(dict[x])
        continue;

    out+=str(incr)
    dict[x]=incr
    incr=incr+1

print out //12345 12324 11123

答案 1 :(得分:1)

如果我正确理解OP,这可能是一个解决方案:

s='areyo uanap ppple'
def trans(word):
    d = {}
    for char in word:
        if char not in d.keys():
            d[char] = len(d.keys()) + 1
        yield str(d[char])
o = ' '.join([  ''.join(trans(word)) for word in s.split(' ')])
print repr(o)

导致:

'12345 12324 11123'

基于unutbu答案的unique,这也是可能的:

' '.join([''.join([ { a:str(i+1) for i,a in enumerate(unique(word)) }[char] for char in word]) for word in s.split(' ') ])

这是另一个,我认为我有点被带走了:))

' '.join([ w.translate(maketrans(*[ ''.join(x) for x in zip(*[ (a,str(i+1)) for i,a in enumerate(unique(w)) ]) ])) for w in s.split(' ') ])

答案 2 :(得分:1)

您可以使用unicode.translate

import string

def unique(seq): 
    # http://www.peterbe.com/plog/uniqifiers-benchmark (Dave Kirby)
    # Order preserving
    seen = set()
    return [x for x in seq if x not in seen and not seen.add(x)]

def word2num(word):
    uniqs = unique(word)
    assert len(uniqs) < 10
    d = dict(zip(map(ord,uniqs),
                 map(unicode,string.digits[1:])))
    return word.translate(d)

s = u'areyo uanap ppple'
for word in s.split():
    print(word2num(word))

产量

12345
12324
11123

请注意,如果一个单词中有超过9个唯一字母,则不清楚您想要发生什么。如果assert传递了这样的话,我就会使用word2num来投诉。

答案 3 :(得分:1)

使用itertools recipes中的unique_everseen()

In [5]: def func(s):
    for x in s.split():
            dic={}
            for i,y in enumerate(unique_everseen(x)):
                     dic[y]=dic.get(y,i+1)
            yield "".join(str(dic[k]) for k in x)    
            dic={}
   ...:             

In [6]: " ".join(x for x in func('areyo uanap ppple'))
Out[6]: '12345 12324 11123'

In [7]: " ".join(x for x in func('abcde fghij ffabc'))
Out[7]: '12345 12345 11234'