简体   繁体   中英

How to fix code repetition and printing only the first line of file?

I am trying to read the file as dictionary and want to print out the outcomes that check whether the input(name) is in the file or not. When I enter a name, it only prints the else statement although the name is in the file and prints the answer hundreds of times. How can I not repeat the same answer over and over? Can you please check my code?

d = {}
count = 0

for i in open("girlnames.txt", "r"):
  (nameG, numberG) = i.split()
  d[nameG] = numberG

count += 1  
print(name, d[name])  
if name in i:
  print("{} is ranked {} in popularity among {} girl names.".format(name, count, d[name]))
else: 
  print("{} is not ranked among the top 1000 girl names.".format(name))
    

Assuming the file is in rank order:

d = {}

for i,line in enumerate(open("girlnames.txt", "r")):
  nameG, numberG = line.split()
  d[nameG] = (i+1, numberG)

print(name, d[name])  
if name in d:
  print("{} is ranked {} in popularity with {}  names.".format(name, d[name][0], d[name][1])
else: 
  print("{} is not ranked among the top 1000 girl names.".format(name))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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