[英]easy python program, not easy for me
我必須寫一個有四種不同文字游戲選項的程序。
其中一個選項是用戶從字典文件中輸入一定長度的單詞,然后程序找到一個具有該長度的單詞,該單詞可以由美國50個州的縮寫組成。
例如:如果用戶輸入6,則程序找到單詞MARINE,其由5個縮寫組成:MA(馬薩諸塞州),AR(亞利桑那州),RI(羅德島州),IN(印第安納州)和NE(內布拉斯加州) 。
到目前為止我有這個:
elif choice == "d":
#wordlen = length of words user is looking for.
wordlen = raw_input("Enter the length of words you are looking for: ")
wordlen = int(wordlen)
print wordlen
states = ['AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI',\
'ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT',\
'NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD',\
'TN','TX','UT','VT','VA','WA','WV','WI','WY']
for line in file:
line = line.strip()
line = line.upper()
if len(line) == wordlen:
我已經在整個循環的開頭打開了字典文件(file = file.open('dictionary.txt')並使用了file.seek(0)然后當循環被打破時(當用戶輸入'q'時) ),file.close(),這樣我就不必在每個過程中打開和關閉文件。
在我有用戶輸入的條件后,我不知道該怎么做。 我已經嘗試了一切,它沒有給我預期的輸出。 請幫忙? 這是我服用python的第一年,這讓我非常困惑-__-
對於具有正確長度的字典文件中的每一行(例如,匹配用戶輸入長度),您需要檢查該單詞中的每個連續字母對,以查看是否在狀態列表中出現。
for line in file:
line = line.strip()
line = line.upper()
if len(line) == wordlen:
# Set some counters/containers.
pair_is_abbrev = 1 #<-- Marks true/false if pair is in abbrev list.
cur_letter_indx = 0 #<-- Counts the location we're at in this line.
# Loop until we find a two-letter sequence that's not an abbrev.
# or until we hit the end of this line (the word length).
while(pair_is_abbrev and cur_letter_indx <= wordlen-1):
cur_pair = line[cur_letter_indx:(cur_letter_indx+2)] #<-- Get current two letters
pair_is_abbrev = (cur_pair in states) #<-- Python way to check if that pair is in your list of abbrevs.
cur_letter_indx = cur_letter_indx + 1 #<-- Increment the counter.
# Once the loop terminates, pair_is_abbrev can only be true if we
# made it all the way to the end of the line successfully. If so,
# then we found an all-abbrevs word. Otherwise, move on to the next line.
if(pair_is_abbrev):
print "Found a word made of abbreviations that is the right length:"
print line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.