Python:检查列表中的任何单词是否存在于文档中

时间:2016-07-07 08:38:17

标签: python list keyword

我正试图'教'自己的Python。目前我正在使用Udacity上提供的免费Python课程。我也在读HTLPTHW。

其中一个模块有点过时,并要求您将URLLIB模块用于现已不存在的网站。根据给定文档中是否存在诅咒词,它所做的是状态True / False。它引用了文件,在读入URL搜索后输入其内容,然后在搜索后解析为True / False。

我正在考虑解决这个问题的方法,我想我可以使用在文档中搜索的发誓列表。如果列表中的发誓也在打开的文档中找到,它会发出警报。

我遇到了一些问题,部分原因可能是我保留了基于教程的大部分原始代码格式 - 这意味着很多可能是针对URLLIB方法而不是关键字搜索。

def read_text():
    quotes = open("/Users/Ishbar/Desktop/movie_quotes.txt")
    contents_of_file = quotes.read()
    print(contents_of_file)
    quotes.close()
    check_profanity(contents_of_file)

def check_profanity(text_to_check):
    Word_db = ["F***","S***","A**"]
    quotes = open("/Users/Ishbar/Desktop/movie_quotes.txt")
    contents_of_file = quotes.read()
    output == Word_db
    if str(Word_db) in quotes.read():
        output == 1
    if output == 1:
        print("Profanity Alert!!")
    elif output == 0:
        print("This document has no curse words.")
    else:
        print("ERROR: Could not scan the document properly.")
read_text()

我无法让代码感到满意。我总是发现亵渎,或者没有发现亵渎。我以为我可以修改输出是什么,输出的默认状态是没有亵渎,除非另有发现。

为此,我是否需要有一个亵渎/缺席的elif,如果它总是缺席,否则存在?

3 个答案:

答案 0 :(得分:1)

由于您已经在read_text()中阅读了该文件的内容,因此您无需再次在check_profanity()

中阅读该文件

此外,行if str(Word_db) in quotes.read():将列表转换为字符串并检查它是否存在于文件中。它相当于:

if '["F***","S***","A**"]' in quotes.read()

您需要检查文件中是否存在列表中的任何元素。这可以使用for循环来完成。

def check_profanity(text_to_check):
    Word_db = ["bad","verybad"]
    if set(Word_db).intersection(set(text_to_check.split())):
        print("Profanity Alert!!")
    else:
        print("This document has no curse words.")

check_profanity("this file contains bad words") # 1st call
check_profanity("this file contains good words") #2nd call

<强>输出:

  

亵渎警告!!

     

这份文件没有骂人的话。

您也可以使用正则表达式执行此操作。

import re
if re.search("("+")|(".join(Word_db)+")", quotes.read()):
   print("Profanity Alert!!")
else:
   print("This document has no curse words.")

答案 1 :(得分:1)

我刚刚遇到了类似的问题(也在做大胆课程)。毫无疑问,您一定会在一段时间前自己解决这个问题,但这最终是我的解决方案。以下来自gaganso,并使用.csv亵渎列表(https://www.frontgatemedia.com/a-list-of-723-bad-words-to-blacklist-and-how-to-use-facebooks-moderation-tool/):

    def read_text():
    text = open("twoSentences.txt")
    contents = text.read()
    #print(contents)
    return(str(contents))
    text.close()

    a_text = read_text()

    def check_curse(sample_text):
    curse_list = open("Terms-to-Block.csv")
    curse_words = str(curse_list.read())  
    sep_text = sample_text.split()
    sep_curses = curse_words.split()
    if set(sep_curses).intersection(set(sep_text)):
        print("ALERT")
    else:
        print("OK")

    check_curse(a_text)

答案 2 :(得分:0)

让我们尝试明确地这样做:

def check_profanity(document_to_check):
    Word_db = ["F***","S***","A**"]
    with open(document_to_check) as quotes:     # let's open the document
        for line in quotes:                     # parse it line by line
            for word in Word_db:                # check offensing words one by one
                if word in line:
                    return True                 # if found one bad word, go out :-)

if check_profanity("/Users/Ishbar/Desktop/movie_quotes.txt"):
    print "Profanity Alert!!"
else:
    print("This document has no curse words.")      

当然,一个经验丰富的python开发人员可以用更少的行重写它,但在神奇地做之前,你必须学会​​如何明确地做到这一点:)