【问题标题】:Search and replace vulgar words in a text by using a text file containing all the bad words使用包含所有坏词的文本文件搜索和替换文本中的粗俗词
【发布时间】:2018-08-10 21:02:33
【问题描述】:
def check_offline(text):
    list_pro = open('full-list-bad.txt','r')

    content = list_pro.readline()
    for ligne in content :
        if ligne in text :
            remplacement = "*" * len(ligne)
            text = text.replace(ligne ,remplacement)
            print ligne

    return text

print check_offline("this is a  shit world " )

【问题讨论】:

  • 您有问题吗?您还应该阅读斯肯索普问题。
  • @jonrsharpe 他不工作,结果中的文字没有改变,
  • 然后edit 的问题来解释这一点;给minimal reproducible example
  • 我找不到如何编辑我的问题!!!
  • 您在问题标签下或我之前的评论中直接点击了“编辑”链接。

标签: python python-2.7


【解决方案1】:

我找到了解决方案,我用拆分方法将txt文件的内容放在了一个列表中,

def check_offline(text):
list_pro = open('full-list-bad.txt','r')

content = list_pro.read()
list_content = content.split('\n')
for word in list_content :
    if word in text :
        remplacement = "*" * len(word)
        text = text.replace(word ,remplacement)
        print word
        print remplacement
return text

print check_offline("这是成人世界")

成人


这是一个****世界

【讨论】:

    【解决方案2】:

    readline 方法只读取一行。

    要么多次调用readline,要么只循环文件对象:

    with open('full-list-bad.txt','r') as list_pro:
        for ligne in list_pro:
            ligne = ligne[:-1]
            if ligne in text:
                # do replacement
    

    抱歉造成混淆,@GarryPolley 对我的代码进行的编辑将其更改为仅调用一次 readline,但没有更改我的评论,即需要多次调用它:/

    【讨论】:

    • 我在其他代码中尝试了 readline(),他逐行读取,我在 python 2 上
    • 可能在您的 other 代码中多次调用它以逐行读取,但在 this 代码中它只读取一行。
    • 你能帮我吗,我不是专业人士,我只是想找到一个答案
    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2013-09-24
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多