如何从文件中获取信息到Python上的字符串?

时间:2016-12-07 23:57:20

标签: python xml file

我在Python上打开了一个文件。该文件加载了以下格式的信息:

    <weight>220</weight>

我使用了分割功能所以我只得到220,这就是我想要的。现在我试图将每行信息放入自己的字符串中。例如,由于此权重信息是第6行,我希望它说

    "The weight of this player is 220 pounds."

这是我到目前为止所做的,但我不确定从哪里开始。有人能够把我推向正确的方向吗?谢谢!

    def summarizeData(filename):
        with open("Pro.txt","r") as fo:
             for rec in fo:
                 print (rec.split('>')[1].split('<')[0])

2 个答案:

答案 0 :(得分:0)

我认为这样做的简单方法就是使用XML解析器,就像johnsharpe所说,所以你的代码就像这样:

from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("Pro.txt")
weights = tree.find("weight") 

然后,一旦你有权重变量设置只是循环并显示你的字符串格式,但你想显示它。

答案 1 :(得分:0)

首先,我建议你使用一个XML解析器,例如ElementTree

但是,对于您的代码,您在filename中进行了位置参数summarizeData但未使用它...尝试这样的事情:

def summarizeData(filename):
    with open(filename,"r") as fo:
        for rec in fo:
            weight_of_player = rec.split('>')[1].split('<')[0]
            print("The weight of this player is %s pounds." % (weight_of_player))

summarizeData("Pro.txt")