Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

How to split each line from file to it's own string in Python?

I have a file with a bunch of information with this following format:

    <name>New York Jets</name>

I am trying to get each line of the file into it's own string. For example, I want this line to say "This is the roster for the New York Jets." I have this so far, but it has "This is the roster for the" for every single line. I think I have to use-

    inputString.split('
')

But I'm not sure where to put it in at. This is what I have so far.

    def summarizeData(filename):
        with open(filename,"r") as fo:
             for rec in fo:
                 name=rec.split('>')[1].split('<')[0]
                 print("Here is the roster for the %s." % (name))

and I call summarizeData("NewYorkJets.txt"). So basically I am trying to split each line from the file to get it in it's own string

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
from xml.dom import minidom

xmldoc = minidom.parse('filename.txt')

itemlist = xmldoc.getElementsByTagName('item')

for s in itemlist: print(s.attributes['name'].value)

you can read a file having tags like this, and retrieve the values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...