Python使用索引方法返回排名

时间:2017-03-20 22:52:23

标签: python python-3.x

我想在文件中显示要搜索的名称的位置。我知道我错过了一些东西,或者说错误地命名了一些东西。

我对Python和编程很新,所以请耐心等待。请解释我错过或做错了所以我可以完成这个程序。提前感谢您的帮助。

try:
     boyfile = open("boynames2014.txt", "r")
     girlfile = open("girlnames2014.txt", "r")

 except IOError:
     print("Error: file not found")



 gender = input("Enter gender (boy/girl): ")
 if gender == "boy" or gender == "girl":
     name = (input("Enter name to search for: "))
 else:
     print("Invalid gender")

 if name in boyfile:
     pos = boyfile.index(name)
     print(name, "was ranked #", pos, "in 2014 for boy names")

 else:
     print(name, "was not ranked in the top 100 boy names for 2014") 

 if name in girlfile:
     pos = girlfile.index(name)
     print(name, "was ranked #", pos, "in 2014 for girl names")

 else:
     print(name, "was not ranked in the top 100 girl names for 2014")




 boyfile.close()
 girlfile.close()

2 个答案:

答案 0 :(得分:0)

当你尝试

if name in boyfile:
对于girlfile,

或者相同,你试图在IOWrapper类元素中检查名称变量名,它不是包含文件内容的列表,它只是这里对文件对象的引用。你需要把内容读到列表

try:
    boyfile = open("boynames2014.txt", "r")
    girlfile = open("girlnames2014.txt", "r")
    boyname_list = [line.strip() for line in boyfile]   #read the content to a list
    girlname_list = [line.strip() for line in girlfile] #read the content to a list

except IOError:
    print("Error: file not found")



gender = input("Enter gender (boy/girl): ")
if gender == "boy" or gender == "girl":
    name = (input("Enter name to search for: "))
    if gender == "boy":
        search_list = boyname_list
    else:
        search_list = girlname_list
    if name in search_list:
        pos = search_list.index(name)
        print(name, "was ranked #", pos, "in 2014 for", gender," names")
    else:
        print(name, "was not ranked in the top 100", gender," names for 2014")
else:
    print("Invalid gender")


boyfile.close()
girlfile.close()

答案 1 :(得分:0)

您可以尝试按照以下步骤阅读boyfilegirlfile的文件和构建列表:作为参考,您可以查看link以获取阅读文件:

try:
    with open("boynames2014.txt", "r") as f:
        boyfile = []
        for line in f:
            boyfile.append(line.strip())

    with open("girlnames2014.txt", "r") as f:
        girlfile = []
        for line in f:
            girlfile.append(line.strip())

except IOError:
     print("Error: file not found")

或者,您也可以使用here中提到的跟随:

try:
    boyfile = [line.strip() for line in open('boynames2014.txt')]
    girlfile = [line.strip() for line in open('girlnames2014.txt')]

except IOError:
    print("Error: file not found")