python - 将缩写词替换为其值 Python

标签 python nlp

我正在清理一些包含大量首字母缩略词的文本。因此,我制作了一本包含一些示例及其值的字典,但是我遇到了一些问题。示例代码如下

    def acr(text):
         acr_dict = {'ft': 'feet'
                      'mi': michigan }
            

         for word, abr in acr_dict.items():
                 text = text.replace(word.lower(), abr)
                 return text

逻辑是有效的,但如果我有一个实例,缩写词的字母也可以在某些其他单词中找到,它将执行以下操作

例如:print(acr('我喜欢牛奶并且住在mi))

输出 --> 我喜欢密歇根州并且住在密歇根州

关于如何不让它查找其他单词中的首字母缩写字母,有什么建议吗?

最佳答案

正如其他人所说,最简单的解决方案是使用正则表达式。

import re

ACR_DICT = {'ft': 'feet', 'mi': 'michigan'}

def acr(text):
    for k, v in ACR_DICT.items():
        text = re.sub(rf'\b{k}\b', v, text)
    return text


acr('I might be 6 ft tall. I often left my home state of mi at 3 years old.')
# 'I might be 6 feet tall. I often left my home state of michigan at 3 years old.'

请注意字边界元字符“\b”的用法。这将确保正则表达式不会在“often”或“might”等单词内找到匹配项。

关于python - 将缩写词替换为其值 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66713265/

相关文章:

google-cloud-platform - 错误: (gcloud.compute.instances.create)无法全局获取资源: - Quota 'GPUS_ALL_REGIONS' exceeded.限制: 0.0

search - 如何获得各种语言中最常用的单词列表?

python - 如何使用 KenLM 计算困惑度?

python - python中int数组中的unsigned char数组

python - 如何在 Python 格式说明符中使用变量名

python - 如何在python中使用flask_restplus在swagger ui上使用*********隐藏密码

python - 如何根据每个组的大小设置滚动窗口大小?

Python - 分组顺序数组成员

nlp - 使用 OpenNLP 的共指解析

Python Pandas cumsum 移位 n