Home > Net >  Replacing multiple words in string from a dictionary
Replacing multiple words in string from a dictionary

Time:05-18

There's a dictionary of abbreviations, the key being the abbreviation and the value being its definition ("TTYL","Talk To You Later"). When user inputs something with more than 1 abbreviation , I want a program to replace the abbreviations with the definition as an addition to the original input. I got the program to work, but only for 1 abbreviation. I want it to be able to handle more than 1 abbreviation in a string. I believe the solution has something to do with the nested for loop, however I'm uncertain and need some help.

Python Code:

abbreviationsDictionary = {
    "ADBA":"As Directed By Arborist",
    "CRTS":"Crown Reduced To Shape",
    "NWIC":"Noob Will Improve Company"
    }

note = input("Enter note: ")
listOfWordsInNote = note.split()

updatedNote = ""
for key in abbreviationsDictionary:
    for word in listOfWordsInNote:
        if (key==word):
            updatedNote = note.replace(key,abbreviationsDictionary[key])

print(updatedNote)

Current Output (only works for 1 abbreviation):

Enter note: mike is going to do whatever ADBA because he knows NWIC
mike is going to do whatever ADBA because he knows Noob Will Improve Company

Desired Output

Enter note: mike is going to do whatever ADBA because he knows NWIC
mike is going to do whatever As Directed By Arborist because he knows Noob Will Improve Company

CodePudding user response:

Rather than replacing in the input string, get the [whitespace delimited] tokens from the user input then use a simple generator to reconstruct:

abbreviationsDictionary = {
    "ADBA": "As Directed By Arborist",
    "CRTS": "Crown Reduced To Shape",
    "NWIC": "Noob Will Improve Company"
}

note = input("Enter note: ")

print(' '.join(abbreviationsDictionary.get(loin, loin) for loin in note.split()))

CodePudding user response:

Your error is that you use

updatedNote = note.replace(key,abbreviationsDictionary[key])

So, each time a new key is found, you restart with note (which has not changed )

just replace by :

            note = note.replace(key,abbreviationsDictionary[key]) 

and print (note) :
mike is going to do whatever As Directed By Arborist because he knows Noob Will Improve Company

  • Related