Bob Unger
Bob Unger

Reputation: 341

How do I check if a string exists in a list

The point of my code is to check a 4 words sentence and whether it is 4 words long.

import random
import time
import urllib

numwords = 4
#getWordList
wordlist = []
def getWordList() :

    url = "some word list url"
    flink = urllib.urlopen(url)
    #print "Reading words from %s" % url
    words = [ ]            # word list
    for eachline in flink :
        text = eachline.strip()
        text = text.replace('%','')
        words += [text.lower()]
    flink.close()
    #print "%d words read" % len(words)
    words.append('i','am','an','to')
    return wordlist


warning = "\n"
prompt = "Enter a sentence with four words: "
while warning:
    usrin = raw_input(warning + prompt)
    usrwords = usrin.strip().lower().split() # a list
    print "The sentence is:", ' '.join(usrwords)
    warning = ''
    if len(usrwords) != numwords: #check length
        warning += ("\n%d words sought; %d obtained \n") %(numwords, len(usrwords))
    invalid = []
    for word in usrwords:
        if word not in wordlist :
            if word not in invalid:
                invalid.append(word)
    if invalid:
        warning += ("\ninvalid words found: %s\n") %(','.join(invalid))

For some reasons it isn't checking my words properly, and it states that every word I enter is invalid. I was also wondering if I appended "I am an to" to the list properly.
Thanks in advance.

Upvotes: 1

Views: 183

Answers (3)

Hyperboreus
Hyperboreus

Reputation: 32429

To answer your original question:

How do I check if a string exists in a list

With the in operator:

>>> a = ['i', 'am', 'here', 42, None, ..., 0.]
>>> 'i' in a
True
>>> 'you' in a
False
>>> 'a' in a
False

Reading a bit your code, it seems you want to identify all the words in one list, which don't figure in the other ("invalid words").

invalid = {word for word in userWords if word not in validWords}

Example:

>>> validWords = ['I', 'am']
>>> userWords = ['I', 'well', 'am', 'well']
>>> {word for word in userWords if word not in validWords}
{'well'}

I was also wondering if I appended "I am an to" to the list properly.

No need to wonder. When you get an error, you are generally not doing it properly:

TypeError: append() takes exactly one argument (4 given)

EDIT

I was so free as to change a bit of your code:

#! /usr/bin/python2.7

NUMWORDS = 4
#you get your wordlist from somewhere else
wordlist = ['i', 'am', 'a', 'dog']

while True:
    usrwords = raw_input("\nEnter a sentence with four words: ").strip().lower().split()
    print "The sentence is: {}".format(' '.join(usrwords))
    if len(usrwords) != NUMWORDS:
        print "\n{} words sought; {} obtained \n".format(NUMWORDS, len(usrwords))
        continue
    invalid = {word for word in usrwords if word not in wordlist}
    if invalid:
        print "\ninvalid words found: {}\n".format(', '.join(invalid))
        continue
    print 'Congratulations. You have entered a valid sentence: {}'.format(' '.join(usrwords))
    #do here whatever you must

Upvotes: 5

Brian Cain
Brian Cain

Reputation: 14619

also wondering if I appended (I am an to) to the list properly.

The wordlist name is first assigned outside of getWordList() at file scope. This is almost certainly not what you want.

Try changing it like so:

def getWordList() :
    url = "some word list url"
    flink = urllib.urlopen(url)

    words = []            # word list
    for eachline in flink.read().split('\n') :
        text = eachline.strip()
        text = text.replace('%','')
        words.append(text.lower())
    flink.close()
    #print "%d words read" % len(words)
    #words.extend('i','am','an','to')
    return words

Also, consider urllib2 instead.

Upvotes: 0

El Bert
El Bert

Reputation: 3026

The line

words.append('i','am','an','to')

should be replaced by one of the following:

words = []
# Add the list ['i','am','an','to'] at the end of the list 'words'
words.append(['i','am','an','to'])
print words # outputs [['i', 'am', 'an', 'to']]
# If you want to add each individual words at the end of the list
words = []
words.extend(['i','am','an','to'])    
print words # outputs ['i', 'am', 'an', 'to']

Upvotes: 1

Related Questions