从 txt 中提取以单词开头的数字。 python 中的文件

Extracting numbers preceded by words from a txt. file in python

我正在尝试从国家名称后的单独文件中提取特定数字。该代码似乎没有显示任何输入,我几乎不知道我在做什么。

它显示输出,但仅显示其他显示无预期寿命数据或无基尼数据的地方。

这是我从

中提取的文件示例
1:      Lesotho                                            :63.2                                              

2:      South Africa                                       :62.5                                              

3:      Central African Republic                           :61.3                                              

4:      Micronesia, Federated States of                    :61.1                                              

5:      Haiti                                              :60.8     

这是我目前的代码

country = []
info = [] 
def countryFinder(fileName,info):

    infile = open(fileName, "r")
    line = infile.readline()

    for line in infile:
        fields = line.split(":")
        country.append(fields[1].strip())
        info.append(fields[2].strip())

        return country, info

userCountry = input("Please enter a country (\"q to quit\"): ")

life = countryFinder("life.txt",info)
gini = countryFinder("gini.txt",info)



while userCountry != "q":
    if userCountry in life:
        print ("  Life Expectancy is ",life[info]," years at birth")
    else:
        print ("  No Life Expectancy Data")

    if userCountry in gini:
        print ("  Gini Value is ",gini[info])
    else:
        print ("  No Gini Data")

    userCountry = input("Please enter a country (\"q to quit\"): ")

软件:spyder python 3.6

你写了一个很好的代码只是到处漏掉了一些行。我用 #

标记了你错过的行
country = []
info = []
dic = {} #
def countryFinder(fileName,info):

    infile = open(fileName, "r")
    line = infile.readline()

    infile = open(fileName, "r").readlines() #

    for line in infile:
        line.strip()
        fields = line.split(":")
        fields = fields[1:3] #
        country = fields[0]
        country = country.strip() #
        info = fields[1]
        info = float(info.strip("\n")) #
        dic[country] = info #
    return dic.copy() #

country = input("Please enter a country (\"q to quit\"): ")
life = countryFinder("life.txt",info)
gini = countryFinder("gini.txt",info)

while country != "q":
    info = life #
    if country in info:
        info = country #
        print ("  Life Expectancy is ",life[info]," years at birth")
    else:
        print ("  No Life Expectancy Data")

    info = gini #
    if country in info:
        info = country #
        print ("  Gini Value is ",gini[info])
    else:
        print ("  No Gini Data")

    country = input("Please enter a country (\"q to quit\"): ")