Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...