2014-03-18 105 views
0

我的代碼的重點是檢查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"正確添加到列表中。
在此先感謝。

+0

很難相信是不是已經回答#2這個問題,但我找不到它。 –

+2

'wordlist'是空的,因爲你永遠不會調用'getWordList'。因此,每一個字都是無效的。 – njzk2

+0

我似乎無法編輯我的代碼,因爲我想出了這個問題,這可能太愚蠢了。我修復了我的詞彙表功能,所以它起作用,我開始用我想追加的詞語開始我的詞彙列表。我忘了在我的while循環中調用我的函數,並且在我這樣做後,我的代碼似乎工作 –

回答

5

要回答你原來的問題:

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

好吧,公平地說,''getWordList()'在給定的代碼中永遠不會被調用,所以它可能是錯誤實際上從未見過。 – femtoRgon

+0

@femtoRgon對。謝謝。親愛的OP,實際上運行你的代碼通常是一個很好的基準,你是否正在做某件事。 – Hyperboreus

+0

你對我的雙重/三重否定支票的評論或者我們確實有效,我只是沒有打電話給我的函數 –

0

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

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代替。

+1

Brian,哪個版本的python正在使用?在我的盒子上,2.x和3.x都會拋出TypeError:append()只需要一個參數(給出4)。 – Hyperboreus

+0

註釋掉(似乎是)調試代碼 –

+0

@Hyperboreus是的,這是問題,所以我開始我的單詞列表,包括那些字符串 –

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

有點我做了什麼。我去了詞= ['我','是','一',']]然後附加到我的網址列表 –

相關問題