我正在尝试“自学”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,如果它总是缺席,否则就会出现?
发布于 2019-06-12 22:50:38
我刚刚遇到了一个类似的问题(也是在做udacity课程)。毫无疑问,你自己在一段时间之前就已经从这个开始了,但这是我最终的解决方案。下面是来自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)
发布于 2016-07-07 16:48:23
让我们试着显式地这样做:
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开发人员可以用更少的代码行重写它,但在神奇地完成它之前,您必须学习如何显式地完成它:)
https://stackoverflow.com/questions/38240963
复制相似问题