如何替换字符串中的符号:



我有下一个代码和下一个文件:

import re

with open("forbidden_words.txt", "r", encoding="utf-8") as stop, open(f'{input()}', 'r', encoding='utf-8') as file:
stop_words = stop.readline().split(" ")
text_file = file.readline()
for i in stop_words:
text_file = re.sub(i, '*'*len(i), text_file, flags=re.IGNORECASE)
print(text_file)

forbidden_words.txt:

warning priority candidate leadership recording judgment law responsibility efficiency advertising imagination department maintenance poet village situation description consequence addition context studio funeral depression entertainment artisan recognition customer understanding writer significance manufacturer administration examination grocery quality sample agency trainer possibility association attention performance childhood refrigerator scene hearing wealth development distribution success delivery presentation relationship grandmother confusion chocolate feedback combination midnight aspect drawer negotiation disease internet speech blood temperature decision baseball recommendation contribution boyfriend introduction historian variety explanation replacement control member operation arrival reading preparation celebration computer painting affair tongue perspective environment communication supermarket construction county establishment inflation engine revolution reality variation engineering application event requirement signature safety history transportation appointment problem interaction conversation information gene improvement politics protection indication proposal personality organization opportunity independence soup leader dealer society teaching language memory height sympathy revenue coffee satisfaction pollution tea preference hello email python exam wor

data.txt

boyfriEND It for have kind, green lesser them doesn him created his moved fruit had.
For whose moved years firmament green image dominion feedback let whales third rule signs midnightblessed light sixth from form for said female land midst and, the likeness.
Fruit evening night for so you called place likeness. Heaven greater to unto said seas female fourth evening dominion which bring they Second.
Two two have.
Heavenmember called fruit form whales saying heaven living firmament unto moved fill appear their.
Form life female, dominion second air won. Cant day.
Morning male to sixth heaven subdue femaleoperation likeness moveth give rule.
hello hearing and wealth. Tooday we development and distribuTIONsucce. The delivery club is the best.
We create PRESENTATION and relationshipwithgrandmother. Please not be confusion, and eatchocolate.

data_2.txt

replacementcontrol MembeR operation    arrival reading preparationcelebration computer.
painting affair tonguePerspect.nvironment proposal......personality!!!!! organization=====
pollution teaPreferencE hello emai python exam wor

data_3.txt

DEVELOPMENT distributionsuccess delivery presentation relationship. Grandmother     confusio  chocolate and feedbackCombination.
historian and math variety explanation...... python PYTHON PyToN

我有以下问题:我的代码没有替换所有需要替换的东西,我应该在我的代码中替换什么来修复它?

with open("forbidden_words.txt", encoding="utf-8") as file, open(input()) as infile:
text = infile.read()
for f in file.read().strip("n").split():
pos = text.lower().find(f)
while pos > -1:
text = text[:pos] + "*" * len(f) + text[pos+len(f):]
pos = text.lower().find(f)
print(text)

在需要使用readline命令时使用了readline命令。

另外,我建议您尝试使用更有意义的名称,这是最佳实践(阅读本文以了解为什么https://towardsdatascience.com/data-scientists-your-variable-names-are-awful-heres-how-to-fix-them-89053d2855be)

例如,你的代码应该看起来像这样:

with open("forbidden_words.txt", "r", encoding="utf-8") as forbidden_file, open(f'{input()}', 'r', encoding='utf-8') as input_file:
forbidden_words = forbidden_file.readline().split(" ")
text_file = input_file.readline()
for forbidden_word in forbidden_words:
text_file = re.sub(forbidden_word, '*'*len(i), text_file, flags=re.IGNORECASE)
print(text_file)

最新更新