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

2024-07-05 14:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码的重点是检查一个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"添加到列表中。
提前谢谢。你知道吗


Tags: textinimporturlif单词listword
3条回答

线路

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

回答您最初的问题:

How do I check if a string exists in a list

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

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

不用奇怪。当您遇到错误时,通常不会正确执行:

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

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

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。你知道吗

相关问题 更多 >