How to check if something is in 2 lists with python -
first of all, gotta code chat bot. giving bot list of words track , i'm splitting messages in room. need make like:
if word list in message.body something.
but attemps failed, code.
leyendotracker = open("listas\eltracker.txt", "r") #open file tracker words buffertracker = leyendotracker.read() #read words , save them in variable leyendotracker.close() #close file s1tracker = set(message.body.split()) #set messages in chat set s2tracker = set(buffertracker) #set variable words file set if s2tracker in s1tracker: #check if word file in message chat. print("[tracker - "+user.name+" said: "+message.body)
that should work in theory, don't understand how sets works , googled problem , converted lists (yes, both lists, not dicts) sets hoping fix problem. nevertheless, surrender after 1 hour of dealing problem.
what missing? :)
use built-in filter function:
>>> hot_words = ["spam", "eggs"] >>> message_body = "oh boy, favourite! spam, spam, spam, eggs , spam" >>> matching_words = filter(lambda word: word in hot_words, message_body.split()) >>> matching_words ['eggs', 'spam'] >>> message_body = "no, i'd rather egg , bacon" >>> matching_words = filter(lambda word: word in hot_words, message_body.split()) >>> matching_words []
splitting string turns list of individual words, , built-in 'filter' takes lambda function argument should returns true or false whether item passed it, should included in result set.
update - answer question think you're asking in comment: after line:
trackeado = filter(lambda word: word in buffertracker, message.body.split())
traceado should list containing words in message match list of words. essentially, need check whether or not list has 0 length or not:
if len(trackeado) > 0: #
update update - ah, i've realised buffertracker isn't list, it's long string read in file. in example, hot_words list of individual words you're looking for. depending on how file formatted, you'll need it, turn list.
e.g. if file comma-separated list of words, this:
>>> words = buffer tracker.split(',') >>> trackeado = filter(lambda word: word in words, message.body.split()) >>> if len(trackeado) > 0: ... print "found"
Comments
Post a Comment