简体   繁体   English

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

[英]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. 我的代码的重点是检查一个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))

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. 我还想知道我是否将"I am an to"到列表中。
Thanks in advance. 提前致谢。

To answer your original question: 要回答您的原始问题:

How do I check if a string exists in a list 如何检查列表中是否存在字符串

With the in operator: 使用in运算符:

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

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

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. 首先在文件作用域的getWordList()之外分配wordlist名称。 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. 另外,请考虑使用urllib2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM