2

我有的:

s='areyo uanap ppple'

我想要的是:

s='12345 12324 11123'

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

4

4 回答 4

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
于 2012-11-21T18:44:41.507 回答
1

if i understand the OP correctly, this might be a solution:

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)

which results in:

'12345 12324 11123'

building on the unique of unutbu answer, this would also be possible:

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

here is another one, i think i got a little carried away :)

' '.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(' ') ])
于 2012-11-21T17:44:27.597 回答
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 个唯一字母,则不清楚您想要发生什么。如果传了这样一个词,我就用 anassert来抱怨。word2num

于 2012-11-21T17:48:30.230 回答
1

使用unique_everseen()来自itertools 的食谱

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'
于 2012-11-21T17:50:22.300 回答