我必须编写一个包含四种不同文字游戏选项的程序。
其中一个选项是用户从字典文件中输入一定长度的单词,然后程序找到一个单词,其长度可以由美国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的第一年,这对我来说非常困惑-__-
答案 0 :(得分:4)
对于字典文件中具有正确长度的每一行(例如,匹配用户输入长度),您需要检查该单词中的每个连续字母对,以查看状态列表中是否出现。
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