当我运行该程序时,它输出的是从该字母开始没有国家存在,而实际上它们存在。有人可以告诉我我做错了什么,或者可能只给我一个替代方式来输出以通缉信开头的国家。这是我的代码:
#Creating the list
CountryList = []
CountryandPopulationList = []
#Creating the Function1
def Function1(fh,letter):
count = 0
#Adding the file to the list
for word in fh:
CountryandPopulationList.append(word)
index = word.find('-')
Country = word[0:index]
CountryList.append(Country.strip())
#Printing countries starting with chosen letter
try:
for i in CountryList:
if(i[1]== letter):
print(i)
count = count + 1
else:
print('The letter does not exist')
except IndexError:
print('Total number of countries starting with letter',letter,'=',count )
#Asking user to input letter
letter = input('Enter the first letter of the country: ')
#Opening the file
try:
fh = open('D:\FOS\\Countries.txt','r')
except IOError:
print('File does not exist')
else:
function1 = Function1(fh,letter)
谢谢
答案 0 :(得分:0)
还请提供您的Countries.txt文件的输入格式以及您正在使用s.t的python版本。它更容易帮助你。
首先:open()不会为您提供文件内容,但只提供textwrapper对象。尝试将行更改为
fh = open('D:\FOS\...\Countries.txt', 'r').read()
答案 1 :(得分:0)
稍微简单的版本。试试这个:
def function1(fh, letter):
count = 0
country_list = [line.split('-')[0].strip() for line in fh.readlines()]
for country in country_list:
if country.lower().startswith(letter.lower()):
count += 1
print(country)
print("Total number of countries starting with letter '%s'= %d" % (letter, count))
#Asking user to input letter
letter = input('Enter the first letter of the country: ')
#Opening the file
try:
with open('D:\FOS\\Countries.txt','r') as fh:
function1(fh, letter)
except IOError:
print('File does not exist')