从txt中提取前面带有单词的数字。 python中的文件

时间:2017-12-10 08:29:51

标签: python file extraction

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

它显示输出但仅显示其中没有预期寿命数据或无基尼数据的其他内容。

以下是我从

中提取的文件示例
sender

这是我到目前为止的代码

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     

软件:spyder with python 3.6

1 个答案:

答案 0 :(得分:0)

你写了一个很好的代码,只是错过了一些线路。我用#

标记了你错过的行
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\"): ")