簡體   English   中英

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

[英]How do I check if a string exists in a 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"到列表中。
提前致謝。

要回答您的原始問題:

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

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

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

還想知道我是否將列表正確地附加到列表中。

首先在文件作用域的getWordList()之外分配wordlist名稱。 幾乎可以肯定這不是您想要的。

嘗試像這樣更改它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM