正则按照单词替换数据

python里替换经常用replace函数,最近发现在清洗数据的时候用到replace有一些问题,后来发现是自己使用不当

比如 "a and a materials" 要把 'a' 'and' 清洗掉,用replace处理后变成"nd mterils"

sp_list = string_input.split()
        for dd in jlx_list:
            for sp in sp_list:
                if sp == dd:
                    # string_input = string_input.replace(dd, "")
                    word_pattern = re.compile(r'\b{0}\b'.format(sp))
                    string_input = re.sub(word_pattern, '', string_input)

  后面发现需要替换完整的单词才可以满足需求,通过正则里的\b匹配完整的单词边界即可满足替换需求

参考 https://www.cnblogs.com/softidea/p/4925577.html

posted @ 2022-03-08 11:00  kakaok  阅读(92)  评论(0)    收藏  举报