python - 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 会忽略“用户”这个词,但我认为需要做其他事情。
解决方案
您可以使用该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)
推荐阅读
- typescript - 打字稿映射类型
- c# - Xamarin.iOS 上的 Swift 框架 - Foundation.MonoTouchException 已被抛出
- python - 如何将标记文本从简单的字符串添加到元素?
- powershell - 是否可以为单个存储库禁用 posh-git?
- python-3.x - 将列的当前值与熊猫数据框中的前一个值进行比较并将结果保存到其他列
- python - opencv python:为什么要这样
- google-apps-script - 如何在 Google Doc Add-on 的 GAS 项目中按名称获取 namedRanges
- node.js - 使用证书中的公钥将引发错误
- machine-learning - h2o: Flow UI, ROC with drf without fold
- java - 如何修复“创建文档实例时出错。原因:org.xml.sax.SAXParseException;必须为元素类型“mapper”声明属性“class”。