使用python替换其值的首字母缩略词 [英] acronym replacement with it's value using python

查看:20
本文介绍了使用python替换其值的首字母缩略词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字典 我需要用它在字典中的值替换文本中的首字母缩略词 我使用这个代码但是当我使用 acronyms("we are gr8 andawsm") 它应该让我觉得我们很棒而且很棒

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

推荐答案

您可以使用 split 将句子分解为单个单词,然后使用简单的列表理解来替换所需的值:

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

输出:

we are great and awesome

这篇关于使用python替换其值的首字母缩略词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆