简体   繁体   中英

How to get info from file into a string on Python?

I have opened a file on Python. The file is loaded with information following this format:

    <weight>220</weight>

I have used the split function so I only get 220, which is what I wanted. Now I am trying to get each line of information put into their own string. For example, since this weight info is the 6th line, I want it to say

    "The weight of this player is 220 pounds."

This is what I have so far, but I'm not sure where to even start. Would anyone be able to push me in the right direction?? Thank you!

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

I think the easy way to do this would be to use an XML parser just like johnsharpe said so your code would be something like:

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

Then once you have the weights variable set just loop through and show your string format however you want to display it.

First of all I would reccommend you use an XML parser such as ElementTree .

However in regards to your code you are taking a positional argument filename in summarizeData but not using it... Try something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM