Home > OS >  Loop a dict with elements from a sentence
Loop a dict with elements from a sentence

Time:10-02

I have a specific text and need to return a number for the specific letter of the alphabet so like a = 1 , b = 2...

I got this code so far... but I do not know how to loop through a dict from a sentence to return( / print ) out the value inside of the sentence inserted

"The sunset sets at twelve o' clock" it returns "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"

def alphabet_position(text):
   Text = text.lower()
   Texting = ''.join([char for char in Text if char.isalpha()])

   place_holder = []

   StrNo = {
     "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}

    #Enter loop
    #Tried using the following lines of code but didn't work
    #listing = list(Texting)
    #answer = "".join([StrNo[Ele] for Ele in listing])
alphabet_position("The sunset sets at twelve o' clock.")

CodePudding user response:

Dictionary is returning an integer element and therefore you are trying to use .join method on integer list which is not possible. Convert integer to string first like this:

answer = "".join([str(StrNo[Ele]) for Ele in listing])

Or you can just use this short snippet:

def alphabet_position(text):
   Text = text.lower()
   Texting = ''.join([char for char in Text if char.isalpha()])

   place_holder = []
   
   listing = list(Texting)
   answer = "".join([str(ord(Ele)-ord('a') 1) for Ele in listing])
   print(answer)
alphabet_position("The sunset sets at twelve o' clock.")

CodePudding user response:

Try this trick, we iterate over each element of dict and use the StrNo attribute ref.

StrNo = {
     "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};

input = "The sunset sets at twelve o' clock".toLowerCase();

result = input.split("").map(x=>StrNo[x]).join(" ");
console.log(result)

Edit: now noticed this is python method!

  • Related