如何在Python中将每一行从文件拆分为自己的字符串? [英] How to split each line from file to it's own string in Python?

查看:95
本文介绍了如何在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('\n')

但是我不确定放在哪里.到目前为止,这就是我所拥有的.

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

,我将其称为summaryData("NewYorkJets.txt").因此,基本上,我正在尝试从文件中拆分每一行,以将其放入自己的字符串中

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

推荐答案

from xml.dom import minidom

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

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

itemlist = xmldoc.getElementsByTagName('item')

itemlist = xmldoc.getElementsByTagName('item')

对于s在项目列表中: 打印(s.attributes ['name'].value)

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

您可以读取具有此类标签的文件,然后检索值.

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

这篇关于如何在Python中将每一行从文件拆分为自己的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆