【发布时间】:2019-05-05 02:08:58
【问题描述】:
我必须创建一个程序,该程序接受用户的状态输入并返回该状态状态花。我必须阅读的以下文本文件称为“state_flowers.txt”,它包含以下数据
California,Poppy
West Virginia,Rhododendron
South Dakota,Pasque Flower
Connecticut,Mountain Laurel
New York,Rose
Georgia,Cherokee Rose
Washington,Coast Rhododendron
Virgina,American Dogwood
Arizona,Saguaro Cactus
Hawaii,Pua Aloalo
Alabama,Camelia
Illinois,Violet
Indiana,Peony
Delaware,Peach Blossom
Iowa,Wild Prairie Rose
Kansas,Sunflower
Alaska,Forget Me Not
Lousiana,Magnolia
Maine,White Pine Tassel
Massachusetts,Trailing Arbutus
Michigan,Apple Blossom
Minnesota,Lady Slipper
Mississippi,Magnolia
Missouri,Hawthorn
Montana,Bitterroot
Nebraska,Goldenrod
Nevada,Sagebrush
New Hampshire,Lilac
New Jersy,Violet
New Mexico,Yucca Flower
etc......
我的代码遇到的问题是,它只会要求输入州名,然后一遍又一遍地继续这样做,而没有输出。到目前为止,这是我的代码:
d = {}
myFile = open('state_flowers.txt', 'r')
for line in myFile:
line2=line.split(",")
state = line2[0]
flower = line2[1]
c = len(flower)-1
#Strips the new line symbol
flower = flower[0:c]
d[state] = flower
#matches each state with its flower
for state, flower in d.items():
search = input("Enter state name:") #user enters input of state
if state == search:
print(flower, "is the State Flower for", state)
正如我所说,我的程序所要求的只是一遍又一遍的输入。所以它是这样的:
Enter state name:Maine
Enter state name:Califorina
Enter state name:Texas
Enter state name:
Enter state name:
我觉得我在这方面非常接近,任何帮助表示赞赏,并且对我做错了什么的清晰解释将不胜感激!谢谢!
【问题讨论】:
-
查看stdlib
csvmodule。无需自己解析文本文件
标签: python python-3.x dictionary