简体   繁体   English

Python - 通过读取文本文件和搜索该字典来创建字典

[英]Python - Creating Dictionaries by reading text files and searching through that dictionary

I must create a program that takes a user's input of a State and it returns that States state flower. 我必须创建一个程序,该程序接受用户对State的输入,并返回States state flower。 The following text file I must read is called "state_flowers.txt" and it contains the following data 我必须阅读的以下文本文件称为“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......

The problem that I'm experiencing with my code is that it will only ask for the input of the state's name and continue to do that over and over again with no output. 我遇到的代码问题是它只会询问状态名称的输入,并且在没有输出的情况下一遍又一遍地继续这样做。 Here is what I have for code so far: 这是我到目前为止的代码:

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)

As I said, all my program asks for is the input over and over again. 正如我所说的,我所要求的所有程序都是一遍又一遍的输入。 So it does as such: 所以它这样做:

Enter state name:Maine
Enter state name:Califorina
Enter state name:Texas
Enter state name:
Enter state name:

I feel as if I'm very close on this, any help is appreciated and a clear explanation of what I am doing incorrectly would be much appreciated! 我觉得好像我非常接近这一点,任何帮助都表示赞赏,并且非常感谢我对错误做出的明确解释! Thank you! 谢谢!

You are close. 你很亲密 There's no need to iterate your dictionary. 没有必要迭代你的字典。 The beauty of dict is it offers O(1) access to values given a key. dict的美妙之处在于它提供了O(1)访问价值的钥匙。 You can just take your input and feed the key to your dictionary: 您可以直接输入并将密钥提供给字典:

search = input("Enter state name:")    #user enters input of state
print(d.get(search), "is the State Flower for", search)

With Python 3.6+, you can write this more clearly using f-strings: 使用Python 3.6+,您可以使用f-strings更清楚地编写它:

print(f'{d.get(search)} is the State Flower for {search}')

If the state doesn't exist in your dictionary d.get(search) will return None . 如果字典中不存在状态,则d.get(search)将返回None If you don't want to print anything in this situation, you can use an if statement: 如果您不想在这种情况下打印任何内容,可以使用if语句:

search = input("Enter state name:")    #user enters input of state
if search in d:
    print(f'{d[search]} is the State Flower for {search}')

Your problem is that in your code: 您的问题在于您的代码:

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)

you loop through all the state/flower pairs, and ask for a state name, each time. 你遍历所有的州/花对,每次都要求一个州名。 So if you have fifty state/flower pairs, the user will be asked fifty times. 因此,如果你有五十个州/花对,用户将被问五十次。 This is not what you want. 这不是你想要的。

Instead, move the line that contains the input(...) statement to outside (that is, before) the loop. 而是将包含input(...)语句的行移动到循环外部 (即之前)。 What way, the loop won't begin until after it's asked for. 什么方式,循环不会它被要求之后开始。

As for the input line and the loop: 至于输入线和循环:

search = input("Enter state name:")    #user enters input of state
for state, flower in d.items():   
    if state == search:                   
        print(flower, "is the State Flower for", state)

consider replacing it with three non-loop lines: 考虑用三个非循环线替换它:

state = input("Enter state name: ")
flower = d[state]
print(flower, "is the State Flower for", state)

And that's it. 就是这样。 There's nothing to manually search for in a loop, since a dict object will search for you. 没有什么可以在循环中手动搜索,因为dict对象将搜索你。

If you're concerned that the user mis-types a state name and you don't want your program to throw an exception, you can change the flower = d[state] line to: 如果您担心用户错误输入状态名称并且您不希望程序抛出异常,则可以将flower = d[state]行更改为:

flower = d.get(state, 'Nothing')

d.get(state) works pretty much the same way as d[state] , except that you can specify what to set flower to (in this case, "Nothing" ) if the state isn't found in the dict. d.get(state)d[state]工作方式几乎相同,只是如果在dict中找不到state则可以指定将flower设置为(在本例中为"Nothing" )。

您可以使用Python 3.6+执行此操作:

print(f'{d.get(search)} is the State Flower for {search}')

You can try a simple debugging. 您可以尝试简单的调试。 Print the values of "state" and "search" just before the comparison condition. 在比较条件之前打印“状态”和“搜索”的值。 This condition isn't getting "True" hence it just iterates for user input: 这个条件没有得到“真”,因此它只是迭代用户输入:

for state, flower in d.items():   
    search = input("Enter state name:")    #user enters input of state
    if state == search: 
        print(state,search)                  
        print(flower, "is the State Flower for", state)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM