Reputation: 55
i have dictionary like that i need to replace acronyms in text with it's value in dictionary i use this code but it doesn't give me the appropriate result when i test the function using acronyms("we are gr8 and awsm")
it should give me we are great and awesome
def acronyms(text):
my_dict = {}
with open('acronym.txt') as fileobj:
for line in fileobj:
key, value = line.split('\t')
my_dict[key] = value
acronym_words = []
words = word_tokenize(text)
for word in words:
for candidate_replacement in my_dict:
if candidate_replacement in word:
word = word.replace(candidate_replacement, my_dict[candidate_replacement])
acronym_words.append(word)
acronym_sentence = " ".join(acronym_words)
return acronym_sentence
Upvotes: 0
Views: 1407
Reputation: 51165
You can use split
to break your sentence into individual words, then a simple list comprehension to replace desired values:
dct = {'gr8': 'great', 'awsm': 'awesome'}
s = "we are gr8 and awsm"
def acronym(s, dct):
return ' '.join([dct.get(i, i) for i in s.split()])
print(acronym(s, dct))
Output:
we are great and awesome
Upvotes: 2