試圖將字母轉換為數字。我正在嘗試做的一個示例是將單詞“green”轉換為相應數字索引值的串列: [6, 17, 4, 4, 13]
我的最終目標是在密碼加密器中使用它,我可以將字母轉換為數字,對數字進行一些數學運算,使它們仍然在 [0, 25] 上,然后將這些數字轉換回字母,所以它混在一起了。
這是我到目前為止所做的代碼:
def lettertonumber(word):
flength = len(word)
fcodera = "abcdefghijklmnopqrstuvwxyz"
fcoderb = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
fcoderlength = len(fcodera)
numkey = []
i = 0
g = 0
while i < flength: # flength is the length of 'word' (in the case of 'green', 5)
while g < fcoderlength: # fcoderlength is the length of the alphabet (26)
if word[i] == fcodera[g]: # to convert it to the number
numkey.append(fcoderb[g]) # fcoderb is a list with [0, 1, 2, 3... 24, 25] for the alphabet
g = g 1
i = i 1
return numkey
word = 'green'
numberkey = lettertonumber(word)
print(numberkey) 的輸出是 [6]。那么,我的問題是考慮我所擁有的回圈,為什么我只在 numberkey[] 中得到一個值得數字的 i 回圈的迭代,而我應該得到與單詞長度一樣多的值(這樣 print( numberkey) 輸出 [6, 17, 4, 4, 13])
抱歉,如果我的問題措辭不佳或沒有幫助,這是我的第一個問題!也為我對 Python 的無知感到抱歉——我昨天才學的!謝謝!
uj5u.com熱心網友回復:
您可以使用該ord函式以十進制獲取 ascii 值,然后減去 97。這一切都可以在串列理解中完成。
>>> word = 'green'
>>> [ord(l.lower()) - 97 for l in word]
[6, 17, 4, 4, 13]
如果您想倒退,您可以獲取數字串列并使用該chr功能轉換回字母。然后用一個空白字串連接在一起。
>>> numbers = [6, 17, 4, 4, 13]
>>> ''.join([chr(n 97) for n in numbers])
'green'
uj5u.com熱心網友回復:
好吧,我還沒有真正完全回答您的問題,但這是一個將數字轉換為字母的簡單函式:
def convert_to_alphabet(number_list):
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet_list = []
for i in number_list:
alphabet_list.append(alphabet[i])
return alphabet_list
uj5u.com熱心網友回復:
我對您的代碼進行了更改。這里是:
def letterToNumber(word):
numKey = []
tmp = 0
for i in word:
tmp = i.lower()
numKey.append(ord(tmp.lower()) - ord('a'))
return numKey
word = 'green'
numberKey = letterToNumber(word)
print(numberKey)
ord()只是將變數名重命名為更清晰,而不是在字母字串中查找索引,我只是使用了可以將字符轉換為ASCII碼值的內置函式。當我得到字符的 ASCII 碼值時,我可以通過減去將其轉換為字母表中的索引ord(character) and ord('a')。
uj5u.com熱心網友回復:
我認為這就是您要搜索的內容:
def lettertonumber(word):
alphabet = []
for i in range(97, 123):
e = chr(i)
alphabet.append(e)
list_of_indexes = []
for i in word:
e = alphabet.index(i)
list_of_indexes.append(e)
print(list_of_indexes)
lettertonumber("green")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478294.html
