簡體   English   中英

用Python中的數字替換單詞中的多個字母?

[英]Replacing multiple letters in a word with number in python?

坎特似乎想出了如何用數字代替字母。 例如

可以說

     'a' , 'b' and 'c' should be replaced by "2".
     'd' , 'e' and 'n' should be replaced by "5".
     'g' , 'h' and 'i' should be replaced by "7".

我要替換的字符串again 我想得到的輸出是27275 這些數字的結果應為字符串。

到目前為止,我已經:

def lett_to_num(word):
    text = str(word)
    abc = "a" or "b" or "c"
    aef = "d" or "e" or "n"
    ghi = "g" or "h" or "i"
    if abc in text:
        print "2"
    elif aef in text:
        print "5"
    elif ghi in text:
        print "7"

^我知道上述錯誤^

我應該寫什么功能?

從字符串使用maketrans:

from string import maketrans
instr = "abcdenghi"
outstr = "222555777"
trans = maketrans(instr, outstr)
text = "again"
print text.translate(trans)

輸出:

 27275

字符串模塊的maketrans提供從instr到outstr的字節映射。 當使用translate時,如果找到了instr中的任何字符,則將其替換為outstr中的相應字符。

這取決於。 既然您似乎在嘗試學習,我將避免對庫的高級使用。 一種方法如下:

def lett_to_num(word):
    replacements = [('a','2'),('b','2'),('d','5'),('e','5'),('n','5'),('g','7'),('h','7'),('i','7')]
    for (a,b) in replacements:
       word = word.replace(a,b)
    return word

print lett_to_num('again')

與您在問題中顯示的代碼嘗試執行的操作接近的另一種方式:

def lett_to_num(word):
    out = ''
    for ch in word:
        if ch=='a' or ch=='b' or ch=='d':
            out = out + '2'
        elif ch=='d' or ch=='e' or ch=='n':
            out = out + '5'
        elif ch=='g' or ch=='h' or ch=='i':
            out = out + '7'
        else:
            out = out + ch
    return out

怎么樣:

>>> d = {'a': 2, 'c': 2, 'b': 2, 
         'e': 5, 'd': 5, 'g': 7, 
         'i': 7, 'h': 7, 'n': 5}

>>> ''.join(map(str, [d[x] if x in d.keys() else x for x in 'again']))
'27275'
>>>
>>> ''.join(map(str, [d[x] if x in d.keys() else x for x in 'againpp']))
'27275pp'
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM