我正在尝试制作一个简单的程序,它接受文本字符串 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/