Python从fi输出内容

2024-05-19 19:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个程序的时候,它输出的结果是没有一个国家是以这个字母开头的,而事实上它们是存在的。有没有人能告诉我我做错了什么,或者给我一个替代方法,只输出从通缉信开始的国家。这是我的密码:

#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)

谢谢


Tags: thetocreatingforcount国家listword
2条回答

稍微简单一点的版本。试试这个:

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')

请同时提供您的输入格式国家.txt文件以及您正在使用的python版本s.t。这更容易帮助您。你知道吗

首先:open()不会提供文件内容,而只提供textwrapper对象。试着把线路改成

fh = open('D:\FOS\...\Countries.txt', 'r').read()

相关问题 更多 >