在 Python 中将字母转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4528982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:09:24  来源:igfitidea点击:

Convert alphabet letters to number in Python

python

提问by altin

How can the following be finished?

如何完成以下内容?

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.

我尝试了很多方法来解决它,但无法解决问题。我想做 exc。如果我输入“你好”,输出将是数字排列的字母表。示例 a = 1 < 在字母表中。

回答by sberry

What about something like this:

这样的事情怎么样:

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

ord
list comprehension
ASCII character codes

ord
列表理解
ASCII 字符代码

EDIT
Since you asked me to explain I will... though it has been explained pretty well in the comments already by [?].

编辑
既然你让我解释,我会......虽然它已经在[?]的评论中解释得很好。

Let's do this in more that one line to start.

让我们从一行开始。

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

This does the same thing, but is more readable. Make sure you can understand what is going on here before you try to understand my first answer. Everything here is pretty standard, simple Python. The one thing to note is the ordfunction. ord stand for ordinal, and pretty much every high level language will have this type of function available. It gives you a mapping to the numerical representation of any character. The inverse function of ord is called chr.

这做同样的事情,但更具可读性。在尝试理解我的第一个答案之前,请确保您能理解这里发生的事情。这里的一切都是非常标准的、简单的 Python。需要注意的一件事是ord函数。ord 代表 ordinal,几乎每种高级语言都有这种类型的函数可用。它为您提供了到任何字符的数字表示的映射。ord 的反函数称为 chr。

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

If you test for yourself, the ordinal of a is 97 (the third link I posted above will show the complete ASCII character set.) Each lower case letter is in the range 97-122 (26 characters.) So, if you just subtract 96 from the ordinal of any lower case letter, you will get its position in the alphabet assuming you take 'a' == 1. So, ordinal of 'b' == 98, 'c' == 99, etc. When you subtract 96, 'b' == 2, 'c' == 3, etc.

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

The rest of the initial solution I posted is just some Python trickery you can learn called list comprehension. But, I wouldn't focus on that as much as I would focus on learning to solve the problem in anylanguage, where ord is your friend. I hope this helps.

我发布的初始解决方案的其余部分只是一些您可以学习的 Python 技巧,称为列表理解。但是,我不会像专注于学习用任何语言解决问题那样专注于此,而 ord 是您的朋友。我希望这有帮助。

回答by parent5446

This is a function I used to use for this purpose. Works for both uppercase and lowercase.

这是我曾经用于此目的的函数。适用于大写和小写。

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

回答by moinudin

>>> [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']

回答by Kabie

Something like this

这样的东西

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

回答by dawg

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']

The first, without commas and what you have in your question, is a one element list with a 26 element string. The second is a 26 element list each a single character in length.

第一个,没有逗号和您在问题中的内容,是一个包含 26 个元素字符串的单元素列表。第二个是一个 26 个元素的列表,每个元素的长度都是一个字符。

If you print each:

如果您打印每个:

>>> 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 char1into an iterable.

很明显,将 的单个字符char1转换为可迭代的需要额外的步骤。

If you have the sequenceof characters 'a' through 'z' and/or 'A' through 'Z', you can easily return the number of the character with list comprehension:

如果您有字符 '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]

So if your code listing is the same as in your question, that may be your issue.

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

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

一个合理的选择是: [ord(x.lower())-96 for x in char1[0]]

You can see that your characters=['a''b''c'...], without the commas, is just the same as typing all the characters in a string in a list like this ['abc...'].

您可以看到characters=['a''b''c'...],不带逗号的 与在这样的列表中键入字符串中的所有字符是一样的['abc...']

So now try:

所以现在尝试:

 >>> 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]]

回答by eyquem

If the goal is to transform only the letters abcd....xyz and ABCD....XYZ , I would use a function:

如果目标是只转换字母 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]

I've written [0:52] because my Python 2.7 version displays the value

我写了 [0:52] 因为我的 Python 2.7 版本显示值

*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz*????????àá??????èéê?ìí??D?òó????ùú?üYT?àáa?????èéê?ìí??e?òó????ùú?üyt?

* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz*????????àá??????èéê?ìí??D?òó????ùú?üYT?àáa?????èéê?ìí??e?òó?? ??ùú?üyt?

for the string.letters argument.

对于 string.letters 参数。

Because the parameter dreceives a value as a default argument, the calculus of this value is performed only once, at the moment when the definition of the function is executed to produce the function object. So, the function can then be used without this value to be calculated again, even if the function is appealed three thousand times.

因为参数d接收一个值作为默认参数,这个值的演算只执行一次,在执行函数定义以生成函数对象的那一刻。因此,即使该函数被调用 3000 次,也可以使用该函数而无需再次计算该值。

By the way, lower() isn't used again for each appeal of the function. The case of upper letters has been treated during the construction of the default argument.

顺便说一下,lower() 不会在函数的每次调用中再次使用。大写字母的大小写已在默认参数的构造过程中得到处理。

.

.

One example of use:

使用示例之一:

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

result:

结果:

s.pe..a....ag...st..e.p.a..d.....s

s.pe..a....ag...st..epa.d....s

.

.

It can be used with map() too :

它也可以与 map() 一起使用:

print map(rank,'ImmunoElectroPhoresis')

result:

结果:

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

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

回答by the wolf

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

The advantage is dictionary lookups are very fast vs iterating over a list on every call.

优点是字典查找非常快,而不是在每次调用时迭代列表。

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

回答by regularex

If you are just looking to map a number to a letter, then just do something simple like this:

如果您只是想将数字映射到字母,那么只需执行以下简单操作:

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.

当然,如果你想让它从 1 开始,那么只需添加 (i+1 for i, ... 等。

回答by ehfgk78

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

here, the index (x) function returns the position value of x if the list contains x.

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

回答by Kurt Maupin

Here's something I use to convert excel column letters to numbers (so a limit of 3 letters but it's pretty easy to extend this out if you need more). Probably not the best way but it works for what I need it for.

这是我用来将 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