Convert alphabet letters to number in Python

如何完成以下工作?

characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z']
numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24']
text = raw_input(' Write text: ')

I've tried to solve it many ways, but couldn't get to the pint. I want to make exc. If I type "hello" the output to be in numbers lined like in alphabet. Example a = 1 < in alphabet.

394235 次浏览

这样如何:

print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]

天啊
列表内涵
ASCII 字符代码

剪辑
既然你让我解释,我就解释... ... 虽然[ ? ]的评论已经解释得很好了.

让我们从多一行开始。

input = raw_input('Write Text: ')
input = input.lower()
output = []
for character in input:
number = ord(character) - 96
output.append(number)
print output

这样做也是一样的,但是更具可读性。在你试图理解我的第一个答案之前,确保你能理解这里发生了什么。这里的一切都很标准,简单的 Python。值得注意的是 ord函数。Ord 代表序数,几乎每种高级语言都有这类函数可用。它为您提供了一个到任何字符的数值表示的映射。奥德的反函数叫做 chr。

chr(ord('x')) == 'x' # for any character, not just x.

如果您自己测试,a 的序号是97(上面我发布的第三个链接将显示完整的 ASCII 字符集)每个小写字母在97-122(26个字符)的范围内因此,如果你只是从任何小写字母的序数中减去96,假设取‘ a’= = 1,你就会得到它在字母表中的位置。所以,‘ b’= = 98,‘ c’= = 99的序数,等等。当你减去96,‘ b’= = 2,‘ c’= = 3,等等。

我发布的最初解决方案的其余部分只是一些叫做列表内涵的 Python 技巧。但是,我不会把注意力放在这上面,我会把注意力放在学习用 任何语言解决问题上,在这里,ord 是你的朋友。希望这个能帮上忙。

这是我用来实现这个目的的函数。它既可以用于大写字母,也可以用于小写字母。

def convert_char(old):
if len(old) != 1:
return 0
new = ord(old)
if 65 <= new <= 90:
# Upper case letter
return new - 64
elif 97 <= new <= 122:
# Lower case letter
return new - 96
# Unrecognized character
return 0
>>> [str(ord(string.lower(c)) - ord('a') + 1) for c in string.letters]
['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', '26', '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', '26']

就像 译自: 美国《每日邮报》网站(https://stackoverflow. com/questions/4319392/python-code-for-計算-number-of-an-alphabet/4319417 # 4319417)

[str(ord(c)&31) for c in text]

Not to be too basic, but this:

>>> char1 = ['a''b''c''d''e''f''g''h''i''j''k''l'
'm''n''o''p''q''r''s''t''u''v''w''x''y''z']

is very different than this:

>>> char2 = ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z']

第一个,没有逗号和你的问题,是一个包含26个元素字符串的一个元素列表。第二个是一个26个元素的列表,每个元素的长度为一个字符。

如果分别打印:

>>> print char1, len(char1), len(char1[0])
['abcdefghijklmnopqrstuvwxyz'] 1 26
>>> print char2, len(char2), len(char2[0])
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q','r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 26 1

It becomes apparent that it takes an additional step to turn the individual characters of char1 into an 可迭代的.

如果你有字符“ a”到“ z”和/或“ A”到“ Z”的 序列,你可以很容易地用 列表内涵返回字符的编号:

>>> [ord(x)%32 for x in char2]
[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, 26]

For the type of data structure you have, you need to access the string first:

>>> [ord(x)%32 for x in char1[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, 26]

因此,如果您的代码清单与您的问题中的代码清单相同,那么这可能是您的问题。

A reasonable alternative is: [ord(x.lower())-96 for x in char1[0]]

您可以看到,没有逗号的 characters=['a''b''c'...]与在类似于 ['abc...']的列表中键入字符串中的所有字符相同。

所以现在试试看:

 >>> import string
>>> [ord(x.lower())-96 for x in string.letters]
[1,2,...26, 1,2,3...26]      # my ellipses
>>> char3=[string.letters]   # one string as element[0]
>>> [ord(x)%32 for x in char3[0]]
>>> [ord(x)%32 for x in [string.letters][0]]

如果目标是只转换字母 ABCD... . XYZ 和 ABCD... . XYZ,我将使用一个函数:

from string import letters
def rank(x, d = dict((letr,n%26+1) for n,letr in enumerate(letters[0:52]))):
return d[x]

我之所以写[0:52]是因为我的 Python 2.7版本显示了这个值

翻译: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对: 奇芳校对:

字符串参数。

因为参数 D接收一个值作为默认参数,所以在执行函数定义以生成函数对象时,这个值的计算只执行一次。 因此,即使这个函数被上诉了三千次,也可以使用这个函数而不需要再次计算这个值。

顺便说一下,对于函数的每个上诉,low ()不会再次使用。在构造默认参数期间处理了大写字母的情况。

.

一个使用的例子:

word = 'supercalifragilisticexpialidocious'
print ''.join( letter if rank(letter)%3!=0 else '.' for letter in word)

结果:

环境保护局

.

It can be used with map() too :

print map(rank,'ImmunoElectroPhoresis')

结果:

[9,13,13,21,14,15,5,12,5,3,20,18,15,16,8,15,18,5,19,9,19]

If you are going to use this conversion a lot, consider calculating once and putting the results in a dictionary:

>>> import string
>>> di=dict(zip(string.letters,[ord(c)%32 for c in string.letters]))
>>> di['c']
3

这样做的好处是字典查找速度非常快,而且每次调用时都可以对列表进行迭代。

>>> for c in sorted(di.keys()):
>>>    print "{0}:{1}  ".format(c, di[c])
# what you would expect....

如果你只是想把一个数字映射到一个字母上,那么就做一些像下面这样简单的事情:

def letter_to_index(letter):
_alphabet = 'abcdefghijklmnopqrstuvwxyz'
return next((i for i, _letter in enumerate(_alphabet) if _letter == letter), None)

Of course if you want to have it start at 1, then just add (i+1 for i, ... etc.

def letter_to_int(letter):
alphabet = list('abcdefghijklmnopqrstuvwxyz')
return alphabet.index(letter) + 1

在这里,如果列表包含 x,index (x)函数返回 x 的位置值。

下面是我用来将 Excel 列的字母转换为数字的方法(所以限制为3个字母,但是如果需要更多的话,可以很容易地将其扩展)。也许不是最好的方式,但它的工作,我需要它的。

def letter_to_number(letters):
letters = letters.lower()
dictionary = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
strlen = len(letters)
if strlen == 1:
number = dictionary[letters]
elif strlen == 2:
first_letter = letters[0]
first_number = dictionary[first_letter]
second_letter = letters[1]
second_number = dictionary[second_letter]
number = (first_number * 26) + second_number
elif strlen == 3:
first_letter = letters[0]
first_number = dictionary[first_letter]
second_letter = letters[1]
second_number = dictionary[second_letter]
third_letter = letters[2]
third_number = dictionary[third_letter]
number = (first_number * 26 * 26) + (second_number * 26) + third_number
return number

可以使用 chr ()和 ord ()在字母和 int 数之间进行转换。

这里有一个简单的例子。

>>> chr(97)
'a'
>>> ord('a')
97

如果您正在寻找相反的例如1 = A,2 = B 等,您可以使用以下代码。请注意,我只去了2级,因为我不得不转换除法在一个类到 A,B,C 等。

loopvariable = 0
numberofdivisions = 53
while (loopvariable <numberofdivisions):
if(loopvariable<26):
print(chr(65+loopvariable))
loopvariable +=1
if(loopvariable > 26 and loopvariable <53):
print(chr(65)+chr(65+(loopvariable-27)))

使用此函数。它将一个字母串转换为它的等效数字值:

def convAlph2Num(sent):
alphArray = list(string.ascii_lowercase)
alphSet = set(alphArray)
sentArray = list(sent.lower())
x = []
for u in sentArray:
if u in alphSet:
u = alphArray.index(u) + 1
x.append(u)
print(x)
return

您可以将字母表映射到一个列表,并按照下面的方式返回每个字母的索引:

import string


alphabet=string.ascii_lowercase
#alphabet='abcdefghijklmnopqrstuvwxyz'


#Get the character index , ex: e
print(chars.find('e'))
#This will return 4
import string
# Amin
my_name = str(input("Enter a your name: "))
numbers      = []
characters   = []
output       = []
for x, y in zip(range(1, 27), string.ascii_lowercase):
numbers.append(x)
characters.append(y)


print(numbers)
print(characters)
print("----------------------------------------------------------------------")


input = my_name
input = input.lower()


for character in input:
number = ord(character) - 96
output.append(number)
print(output)
print("----------------------------------------------------------------------")


sum = 0
lent_out = len(output)
for i in range(0,lent_out):
sum = sum + output[i]


print("resulat sum is : ")
print("-----------------")


print(sum)










resualt is :
[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, 26]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
----------------------------------------------------------------------
[1, 13, 9, 14]
----------------------------------------------------------------------
resulat sum is :
-----------------
37

这是一个非常简单的脚本,可以按照您的要求完成任务:

#!/usr/bin/env python3


def remove(string):
return string.replace(" ", "")


dict = {'a': '1',
'b': '2',
'c': '3',
'd': '4',
'e': '5',
'f': '6',
'g': '7',
'h': '8',
'i': '9',
'j': '10',
'k': '11',
'l': '12',
'm': '13',
'n': '14',
'o': '15',
'p': '16',
'q': '17',
'r': '18',
's': '19',
't': '20',
'u': '21',
'v': '22',
'w': '23',
'x': '24',
'y': '25',
'z': '26',
}


word = remove(input(''))


for x in word:
print(dict[x])


## or ##
#index = 0
#for x in word:
#   print(dict[word[index]])
#   index = index + 1
characters = 'abcdefghijklmnopqrstuvwxyz'
d = {}
for x in range(len(characters)):
d[characters[x]] = x+1


print(d)

prints {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}

print(d['a']) # 1
print(d['z']) # 26

用字母上的数字31执行 AND 操作就可以了。

这里有一个例子:

str1 = 'abcdefABCDEF'
list1 = []


for i in str1:
list1.append(ord(i) & 31)
print(list1)


for j in range(0, len(list1)):
print(chr(list1[j] + 64), end = '')

这样做的结果将是:

[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
ABCDEFABCDEF