Python不会忽略文件中的单词

时间:2019-10-03 21:50:12

标签: python

我是python的新手,所以我经常被卡住,如果这很容易解决,请告诉我。

我正在一个项目中,我的程序将识别并比较文件中的单词。我以为这对像我这样的初学者来说会很容易,但是我的问题是该程序将“ User”识别为用户,并且我可能非常挑剔,但这让我感到恼火。

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

import socket

from . import requests_wrapper as requests  # Use this load the patch


# This will work (if IPv6 connectivity is available) …
requests.get("http://ip6only.me/", family=socket.AF_INET6)
# … but this won't
requests.get("http://ip6only.me/", family=socket.AF_INET)

# This one will fail as well
requests.get("http://127.0.0.1/", family=socket.AF_INET6)

# This one will work if you have IPv4 available
requests.get("http://ip6.me/", family=socket.AF_INET)

# This one will work on both IPv4 and IPv6 (the default)
requests.get("http://ip6.me/", family=socket.AF_UNSPEC)

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

1 个答案:

答案 0 :(得分:0)

您可以像这样使用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)