如何在Python上把文件中的信息转换成字符串?

2024-05-15 23:43:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我打开了一个关于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])

Tags: 文件ofthe函数字符串信息is格式
2条回答

我认为最简单的方法是使用一个XML解析器,就像johnsharpe所说的那样,这样您的代码将类似于:

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

一旦设置了weights变量,只需循环并显示字符串格式,不管您希望如何显示它。你知道吗

首先,我建议您使用ElementTree这样的XML解析器。你知道吗

然而,对于您的代码,您在summarizeData中使用位置参数filename,但不使用它。。。尝试以下操作:

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

相关问题 更多 >