从网站添加人口

时间:2015-11-16 01:21:00

标签: python python-3.x text-files

此程序旨在向用户询问州开始的一个或多个字母。当它有输入时,它会显示该状态的信息,包括来自网络的人口和平方公里面积。当用户输入有多个结果时,我需要该程序为总体人口和面积提供总数。即。用户类型: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")

1 个答案:

答案 0 :(得分:0)

for item in float(item_list[3]):
    total_pop += pop
for item in int(item_list[2]):
    total_area += area

在这段代码中,你试图迭代一个浮点数和一个int,这是不允许的,因为你只能迭代列表,字典等。你也试图打印total_area和total_pop这些是局部变量函数外的函数“find_starts_with”。如果要在函数外部打印它们,请将它们声明为全局或返回值。

以下是更正后的代码:

    #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