输出在字符串中找到的特定单词(来自列表)

Output the specific word (from a list) that was found in a string

我正在尝试识别在字符串句子中识别出的特定单词(从列表中)。

我已经设法导入了一个(不适当的)单词列表,然后将其与输入句子进行比较,以查看该单词是否在句子中(在基本 if 循环中使用)- 它运行良好(下面的代码),但现在我需要确定实际找到的单词用作输出的一部分。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from inappropriate_words import inappropriate # a list of inappropriate words
import sys

message = ' '.join(sys.argv[1:]) # the input message already converted to lowercase
message = message.replace(".", "") # to remove the full stop as well
#print (message) #to test if needed

if any(word in message.split() for word in inappropriate):
    print "SAMPLE WORD is inappropriate."

例如:
输入:"Do you like cookies"
过程:Cookies 在不合适的列表中,因此被识别并触发 if 循环
输出:"Cookies is inappropriate." # 我喜欢饼干 SBTW

我会使用一个集合来存储不合适的单词,然后简单地使用列表进行 O(1) 而非 O(n) 的查找:

st = set(inappropriate)
message = ' '.join(sys.argv[1:]) # the input message already converted to lowercase
message = message.replace(".", "") # to remove the full stop as well

for word in message.split():
    if word in st:
        print "{} is inappropriate.".format(word)

如果您想查看是否有任何单词匹配,请添加一个分隔符,以查看所有匹配的单词按原样使用。

您还可以使用set.intersection查找所有常用词:

comm = st.intersection(message.split()) 

最后,您可以去掉单词中的标点符号并使用 argv[1:] :

,而不是合并和替换
from string import punctuation

from inappropriate_words import inappropriate # a list of     inappropriate words
import sys

for word in sys.argv[1:]:
    if word.strip(punctuation) in st:
        print "{} is inappropriate.".format(word)