从网站添加人口

adding population from a website

此程序旨在向用户询问状态开头的一个或多个字母。当它有这个输入时,它会从网络上调出关于该州的信息,包括人口和平方公里的面积。当用户输入有多个结果时,我需要程序为我提供人口和面积总数。 IE。用户输入:c,得到加利福尼亚、科罗拉多、康涅狄格等。我只需要它在显示的所有结果结束时打印一次总计。我试图在定义 find_starts_with 中添加我希望它执行的操作,但没有成功。

这可能是一个简单的修复,但我对 python 还是比较陌生,非常感谢任何帮助。

    #p6 states 
    #reads text file from the web
    state_list=[]
    import urllib.request

def read_file(url):
    """ reads the url and returns a unicode txt file"""
    with urllib.request.urlopen(url) as webpage: #opens the webpage
        for line in webpage:
            line= line.strip()
            line= line.decode('utf-8')#unicode
            if line [0] != "#":
                item_list =line.split(',')#splits list at comma
                state= item_list[0].lower()
                capital = item_list[1].lower()
                area=int(item_list[2])
                pop= float(item_list[3])
                state_list.append([state, capital, area, pop])
    return state_list   
        #end if
    #end for
#end with
#----------------------------------------------------------------
def find_starts_with(start_letters, state_list):
    """ searches  text file to find a state beginning with the letters     entered"""
        print()
    found= False
    n_to_match=len(state_to_find)
    for item_list in state_list:
        state= item_list[0].lower()
        if state_to_find == state[0:n_to_match]:

            total_pop = 0.0
            total_area = 0
        if state_to_find == state[0:n_to_match]:
            print_state=state.title()
            capital = item_list[1]
            print_capital = capital.title()
            area = int(item_list[2])
            print_area = format(area, '10,d') # 10 spaces, show commas
            pop = float(item_list[3])
            print_pop = format(pop, '10,.1f')
            found= True
            for item in float(item_list[3]):
                total_pop += pop
            for item in int(item_list[2]):
                total_area += area
            print(print_state, "capital: ", print_capital, "\n",
                  print_area, "sq km\n   ",
                  print_pop, "million people\n")
    print("total area", total_area, "Total population ", total_pop)   


    if not found:
        print("don't you know how to spell your states correctly? ")
    return None

#-----------------------------------------------------------------------



#-----------------------------------------------------------------------
url = "http://www.cs.uoregon.edu/classes/15F/cis122/data/state_data.txt"
state_list= read_file(url)


request=input("type the first few letters of a states name or type q to quit ")
while request != 'q':
    state_to_find=request
    state_to_find= state_to_find. lower()
    find_starts_with(state_to_find, state_list)
    print ("total area: ", total_area, "\n Total population: ", total_pop)
    request= input("type the first few letters of a states name or type q to quit ")

if request=='q':
    print("have a nice day")
for item in float(item_list[3]):
    total_pop += pop
for item in int(item_list[2]):
    total_area += area

在这部分代码中,您试图遍历一个浮点数和一个整数,这是不允许的,因为您只能遍历列表、字典等。您还试图打印 total_area 和total_pop 是函数 "find_starts_with" 在函数外的局部变量。如果您想在函数外打印它们,请将它们声明为全局或 return 值。

这是更正后的代码:

    #p6 states 
    #reads text file from the web
state_list=[]
import urllib.request

def read_file(url):
    """ reads the url and returns a unicode txt file"""
    with urllib.request.urlopen(url) as webpage: #opens the webpage
        for line in webpage:
            line= line.strip()
            line= line.decode('utf-8')#unicode
            if line [0] != "#":
                item_list =line.split(',')#splits list at comma
                state= item_list[0].lower()
                capital = item_list[1].lower()
                area=int(item_list[2])
                pop= float(item_list[3])
                state_list.append([state, capital, area, pop])
                #print(state_list)
    return state_list   
        #end if
    #end for
#end with
#----------------------------------------------------------------
def find_starts_with(start_letters, state_list):
    """ searches  text file to find a state beginning with the letters     entered"""
    print()
    found= False
    n_to_match=len(state_to_find)
    total_pop = 0
    total_area = 0
    for item_list in state_list:
        state= item_list[0].lower()
        if state_to_find == state[0:n_to_match]:

            total_pop = 0.0
            total_area = 0
        if state_to_find == state[0:n_to_match]:
            print_state=state.title()
            capital = item_list[1]
            print_capital = capital.title()
            area = int(item_list[2])
            print_area = format(area, '10,d') # 10 spaces, show commas
            pop = float(item_list[3])
            print_pop = format(pop, '10,.1f')
            found= True
            total_pop += pop
            total_area += area
            print(print_state, "capital: ", print_capital, "\n",
                  print_area, "sq km\n   ",
                  print_pop, "million people\n")
    #print("total area", total_area, "Total population ", total_pop)   


    if not found:
        print("don't you know how to spell your states correctly? ")
    return total_pop,total_area

#-----------------------------------------------------------------------



#-----------------------------------------------------------------------
url = "http://www.cs.uoregon.edu/classes/15F/cis122/data/state_data.txt"
state_list= read_file(url)


request=input("type the first few letters of a states name or type q to quit ")
while request != 'q':
    state_to_find=request
    state_to_find= state_to_find. lower()
    total_pop,total_area=find_starts_with(state_to_find, state_list)
    print ("total area: ", total_area, "\n Total population: ", total_pop)
    request= input("type the first few letters of a states name or type q to quit ")

if request=='q':
    print("have a nice day")

输出:

type the first few letters of a states name or type q to quit c

California capital:  Sacramento 
    423,970 sq km
          38.3 million people

Colorado capital:  Denver 
    269,601 sq km
           5.2 million people

Connecticut capital:  Hartford 
     14,357 sq km
           3.6 million people

total area:  14357 
 Total population:  3.6
type the first few letters of a states name or type q to quit cali

California capital:  Sacramento 
    423,970 sq km
          38.3 million people

total area:  423970 
 Total population:  38.3
type the first few letters of a states name or type q to quit q
have a nice day