【问题标题】:acronym replacement with it's value using python使用python用它的值替换首字母缩写词
【发布时间】:2018-05-09 18:05:33
【问题描述】:

我有这样的字典,我需要用字典中的值替换文本中的首字母缩略词太棒了

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

【问题讨论】:

    标签: python twitter sentiment-analysis


    【解决方案1】:

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

    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
    

    【讨论】:

    • 或类似:re.sub(r'\b({})\b'.format('|'.join(dct)), lambda m: dct[m.group(0)], s)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多