如何检查列表中是否存在字符串

时间:2014-03-18 19:51:35

标签: python string list

我的代码的重点是检查4个单词的句子以及是否长4个单词。

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))

由于某些原因,它没有正确检查我的单词,并且它说明我输入的每个单词都是无效的。我还想知道我是否正确地将"I am an to"添加到列表中 提前谢谢。

3 个答案:

答案 0 :(得分:5)

回答你原来的问题:

  

如何检查列表中是否存在字符串

使用in运算符:

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

读一下你的代码,似乎你想要识别一个列表中的所有单词,而不是另一个单词中的单词(“无效单词”)。

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

示例:

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

  

我也想知道我是否正确地将“我是一个”添加到列表中。

无需怀疑。当您收到错误时,通常无法正常执行此操作:

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

修改

我可以自由地改变你的一些代码:

#! /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

答案 1 :(得分:1)

该行

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

应替换为以下之一:

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']

答案 2 :(得分:0)

  

还想知道我是否正确地将(我是一个)附加到列表中。

wordlist名称首先在文件范围的getWordList()之外分配。这几乎肯定不是你想要的。

尝试改变它:

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

另外,请考虑urllib2