python - 使用字典审查文本字符串并用 X 替换单词。 Python

标签 python dictionary

我正在尝试制作一个简单的程序,它接受文本字符串 t 和单词列表 l 并打印文本,但包含 t 中的单词>l 替换为与单词中的字母相对应的多个 X。

问题:我的代码还替换了与 l 中的单词匹配的部分单词。我怎样才能让它只针对整个单词?

def censor(t, l):

    for cenword in l:
        number_of_X = len(cenword)
        sensurliste = {cenword : ("x"*len(cenword))}

        for cenword, x in sensurliste.items():
            word = t.replace(cenword, x)
            t = word.replace(cenword, x)

    print (word)

最佳答案

另一种方法是使用正则表达式来获取所有单词:

import re

blacklist = ['ccc', 'eee']

def replace(match):
    word = match.group()
    if word.lower() in blacklist:
        return 'x' * len(word)
    else:
        return word

text = 'aaa bbb ccc. ddd eee xcccx.'

text = re.sub(r'\b\w*\b', replace, text, flags=re.I|re.U)
print(text)

这具有处理正则表达式识别的各种单词边界的优点。

关于python - 使用字典审查文本字符串并用 X 替换单词。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675634/

相关文章:

bash - 从 bash 映射中检索时如何区分 null 和空字符串

Python:将列表添加到字典中并在列表中填充零

dictionary - Clojure:将元素添加到 map 内的向量中

Python Aiohttp Asyncio : how to create delays between each task

python - 如何在 Python 的 tempfile.TemporaryFile() 中指定文本模式?

Python OLA 类型错误 : can only assign array

python - ReportLab 有可流动的 matplotlib 吗?

python - 查找字典中的值变化和索引

python - 给定字典中的键,提取 x 个先前的键值对

Python Beautiful Soup find_all