首页 > 解决方案 > Python 不会忽略文件中的单词

问题描述

我对python很陌生,所以我经常被卡住,如果这很容易解决,请告诉我。

我正在做一个项目,我的程序将识别和比较文件中的单词。我认为这对于像我这样的初学者来说很容易,但我的问题是程序将“用户”识别为用户,我可能非常挑剔或其他什么,但这让我很恼火。

这是我从另一个 StackOverflow 问题中尝试的代码,但它似乎不适用于文件读取。

import re

mytext = open ("Secret.txt", "r")

#The Text i'm gonna ignore                   
r_items=['User']

mytext = [x for x in mytext if x not in r_items]

我所期望的是 Python 会忽略“用户”这个词,但我认为需要做其他事情。

标签: python

解决方案


您可以使用该str.replace方法,如下所示。

banned_words = ['User']

# Always use `with` to open files, 
# so it's automatically closed when finished.
with open('Secrets.txt') as f:
    # Read all the text into a string.
    text = f.read()

# Iterate over the banned words.
for banned_word in banned_words:
    # Reassign `text` to the new version without `banned_word`.
    text = text.replace(text, banned_word, '')

print(text)

推荐阅读