使用python将字母转换为数字

2024-09-24 04:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我所拥有的:

s='areyo uanap ppple'

我想要的:

^{pr2}$

我应该用字典翻译i中的每一个s.split(' ')?或者有更简单的方法吗?在


Tags: 方法字典splitpr2uanappppleareyo
3条回答

使用来自itertools recipesunique_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'
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

您可以使用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))

收益率

^{pr2}$

请注意,如果一个单词中有9个以上的唯一字母,您不清楚您想要发生什么。我用了一个assert来抱怨word2num是否被传递了这样一个词。在

相关问题 更多 >