gpt4 book ai didi

python - 如何替换与我的字符串列表匹配的单词(在 txt 文件中)?

转载 作者:行者123 更新时间:2023-12-04 15:31:30 24 4
gpt4 key购买 nike

  • 我希望了解如何从我的 .TXT 文件中替换某些单词。
    • 那些特定的词将是 censored_words 列表中的字符串。

我成功地替换了一个单词:

email = open('email.txt', 'r').read()

def single_string_replace(email):
return email.replace('word1', 'REDACTED')

但我无法获得“完美”工作的单词列表。这是我的尝试:

email = open('email.txt', 'r').read()
banned_words = ['word1', 'phrase one']

def list_replace(email):
list_place = 0
while list_place < len(banned_words):
for word in banned_words:
email = email.replace(word, 'REDACTED')
list_place += 1
return email

我希望保持 .TXT 文件不变,并且只通过 print() 语句查看更改,例如

print(list_replace(email))

我遇到的问题是:

  • 假设我禁用了“dog”这样的词,还禁用了“hotdog”这个词。如果“dog”在列表中排在第一位,那么当搜索“hotdog”以查找 ban 时,它不会找到任何内容。
  • 这会创建“hotREDACTED”而不是“REDACTED”。
  • 反之亦然。如果我想禁止使用狗这个词,但可以使用热狗,我如何才能确保上述两种情况都正常工作?

一如既往、现在和将来:欢迎所有建议!

谢谢

最佳答案

你可以使用 re.sub :

import re


email = open('email.txt', 'r').read()
banned_words = ['word1', 'phrase one']
pattern = '|'.join(f'\\b{w}\\b' for w in banned_words)

def list_replace(email):
return re.sub(pattern, 'REDACTED', email)

print(list_replace(email))

关于python - 如何替换与我的字符串列表匹配的单词(在 txt 文件中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61178196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com