【问题标题】:How to replace symbols in string:如何替换字符串中的符号:
【发布时间】:2021-11-15 18:50:46
【问题描述】:

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

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

数据.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

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

【问题讨论】:

  • readline() 读取一行。
  • 您应该包括输出示例和预期输出。它替代了什么,不替代什么?
  • 使用file.read()。您可能还想使用:text_file = re.sub(fr'\b{i}\b', '*'*len(i), text_file, flags=re.IGNORECASE),这样您就不会更改“inlaw”之类的词。

标签: python string list file re


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    当你需要使用 readlines 推荐时,你使用了 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-23
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 2015-04-16
      相关资源
      最近更新 更多