此源代码的目标是仅打印国家/地区和国家/地区名称。我是Python的新手并使用CSV和数据库,但我被告知in a code review以CSV格式存储数据会更好。
已解决:还有另一个问题。在询问某个国家/地区时,无论您输入的是正确还是错误的国家/地区,它仍然会被视为不在列表中。
源代码:
import random
import csv
print '\nCountries to choose from are\n'
country_list = []
with open('countries.csv', 'rb') as csvfile:
countryreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for idx, country in enumerate(countryreader):
print ' '.join(country) # everything besides population and country title should be hidden
if (idx != 0): # Don't append the fist row (column headers)
country_list.append(country[0])
startcountry = raw_input('\nWhat country would you like to start in? If you can\'t think of one, you can enter random to choose a random country.').title()
if startcountry == 'Random': # random.sample can be used for more than one country later on
startcountry = random.choice(country_list)
while startcountry not in country_list:
startcountry = raw_input('We don\'t know that country. Please enter one from the list above. ')
CSV文件:
Country,Population,Type
China,1363560000,Urban
India,1242070000,Rural
United States,317768000,Urban
Indonesia,249866000,Rural
Brazil,201032714,Rural
Pakistan,186015000,Unspecified
Nigeria,173615000,Unspecified
Bangladesh,152518015,Unspecified
Russia,143700000,Rural
Japan,127120000,Urban
Mexico,119713203,Urban
Philippines,99329000,Unspecified
Vietnam,89708900,Unspecified
Egypt,86188600,Unspecified
Germany,80716000,Urban
Iran,77315000,Unspecified
Turkey,76667864,Unspecified
Thailand,65926261,Unspecified
France,65844000,Urban
United Kingdom,63705000,Urban
Italy,59996777,Urban
South Africa,52981991,Unspecified
South Korea,50219669,Unspecified
Colombia,47522000,Rural
Spain,46609700,Unspecified
Ukraine,45410071,Rural
Kenya,44354000,Unspecified
Argentina,40117096,Rural
Poland,38502396,Rural
Sudan,37964000,Rural
Uganda,35357000,Unspecified
Canada,35344962,Unspecified
Iraq,34035000,Unspecified
答案 0 :(得分:1)
这是因为您使用空格作为分隔符,但您的csv文件使用逗号作为分隔符。
更改
countryreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
到
countryreader = csv.reader(csvfile, delimiter=',', quotechar='|')
无论如何,我认为你使用了错误的数据结构,如果你read your CSV file to a dictionary那么你可以轻松访问国家名称和人口。