Assigning numbers to given string's letters

Viewed 147

I am currently trying to finish a project which wants encode given paragraph using given matrix. I wanted to start make a letter list:

letterlist = np.array([" ","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"])
letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY"

My goal is convert the letters to integer in order like A=1,B=2...Z=26 and " "=0. Then assign them to 1x3 arrays. like enter image description here

But I couldn't even make a progress. First I tried make for loops to match same letter in the letter list and samplestr. Then if they are same, give the order in the letterlist as integer. But I didn't get any output.

for letter in samplestr:
    for letter2 in letterlist:
        if letter2==letter:
            print("x") ## To see if I get any match

I don't know where did I wrong and how should I continue this. Would making dictionary make it easier to assign letters to integers? Need some advices. Thanks for your time.

4 Answers

The conversion to a number is done by converting the char to a ordinary number and then subtracting 64 because that is the starting ASCII-Index for 'A'

Code looks like this:

from math import ceil

samplestr = "MEET ME MONDAY"

# Pad string to be dividable by 3 
samplestr = samplestr.ljust(ceil(len(samplestr)/3) * 3)
# "MEET ME MONDAY "

# Convert to number reprensentation
samplestr = [0 if c == ' ' else (ord(c)-64) for c in samplestr]
# [13, 5, 5, 20, 0, 13, 5, 0, 13, 15, 14, 4, 1, 25, 0]

# Split in chunks of 3
matrix = [samplestr[i:i+3] for i in range(0, len(samplestr), 3)]
print(matrix)

This produces the following output:

[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]

Yes, dictionary will make it easier to assign letters to integers but if your final goal is to convert the letters to integer in order like A=1, B=2...Z=26 and " "=0, then assigning indices to the letters will also do the job.

I don't have much knowledge of numpy, so I will do it simply like this:

letterlist2 = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
samplestr = "MEET ME MONDAY "

l = []
s = []
for i in samplestr:
    s.append(letterlist2.index(i))
    if len(s) == 3:
        l.append(s)
        s = []

if s != []:
    l.append(s)
print(l)

Output:

[[13, 5, 5], [20, 0, 13], [5, 0, 13], [15, 14, 4], [1, 25, 0]]

Use a dictionary (with a single list comprehension) to convert the letters to numbers (would probably be the fastest) and then reshape to have 3 columns (-1 will take care of number of rows):

convert = dict(zip(letterlist, np.arange(27)))
converted = np.array([convert[char] for char in samplestr])
#[13  5  5 20  0 13  5  0 13 15 14  4  1 25]
from math import ceil
#resize to closes upper multiple of 3
converted.resize(ceil(converted.size/3)*3)
#reshape to have 3 columns
converted = converted.reshape(-1,3)

output:

[[13  5  5]
 [20  0 13]
 [ 5  0 13]
 [15 14  4]
 [ 1 25  0]]

Here is another solution with a simple dictionary mapping and list comprehensions. Note that you don't need to hardcode letters, it's in the standard library.

from string import ascii_uppercase

chars = " " + ascii_uppercase

encode = {char:"{}".format(i) for i, char in enumerate(chars)}

def str2num(s):
    return [[encode[char] for char in s[i:i+3]] for i in range(0, len(s), 3)]


s = "MEET ME MONDAY"
print(str2num(s))

which returns:

[['13', '5', '5'],
 ['20', '0', '13'],
 ['5', '0', '13'],
 ['15', '14', '4'],
 ['1', '25']]
Related