试图理解埃莱曼人

2024-04-19 20:31:15 发布

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

我正试图对xml文件(我的文本消息)做一些简单的修改,但是我很难理解到底发生了什么以及为什么

我的xml文件格式如下:

<sms count="123456" backupset="123456" backupdate="12345"....>
     <sms protocol="0" address="51511" date="1531363846440" type="1" subject="null" body="Welcome to Family Mobile! Your number is: ....>
     <sms protocol="0" address="58038" date="1531407417581" type="1" subject="null" body="Family Mobile Important Message:...>
...

因此,当我创建一棵树时:

import xml.etree.ElementTree as ET
import os

os.chdir('C:/Users/Sams PC/Desktop/')

tree = ET.parse("text_messages.xml")
root = tree.getroot()

我的根标签和属性是:

>>>root.tag
'smses'
>>> root.attrib
{'count': '6079', 'backup_set': '1233456', 'backup_date': '12345'}>>>

因此,我的子节点将是sms,即:

for child in root:
...     print(child.tag, child.attrib)
...
sms {'protocol': '0', 'address': '51511', 'date': '1531363846440', 'type': '1', 'subject': 'null', 'body': 'Welcome to Family Mobile! Your number is: ...}
sms {'protocol': '0', 'address': '58038', 'date': '1531407417581', 'type': '1', 'subject': 'null', 'body': 'Family Mobile Important Message: ...}

所以,如上所述,我想做的是从特定的数字中选择文本。所以这是我的方法

for sms in root.findall('sms'):
    address=sms.get('address')
    if address != 51511:
        root.remove(sms)


tree.write('output.xml')

所以基本上,我们的想法是,搜索并获取短信行地址中的每个值,然后过滤这些地址,如果该值不等于12345,则删除整个短信行(换句话说,只保留文本编号12345)

然而,我的输出文件却删除了每一行sms(即使是地址值为12345的行,也会得到一个空白文件)。有趣的是,如果我将删除改为address==12345,那么我的输出文件将包含每个地址及其正文(因此它删除日期、协议、类型和主题)

if address == 51511:
        root.remove(sms)

#output is:

<sms address="51511" body="Welcome to Family Mobile! Your number is:..>

在这一点上,我不知道为什么我得到我得到的输出,我觉得我一定误解了这个元素树是如何工作的。任何帮助都将不胜感激!谢谢你

编辑: 我只想补充最后一点,我相信这里的问题是,它说没有地址=='该值' 也就是说,如果我这样做:

for sms in root.findall('sms'):
    address=sms.get('address')
    body=sms.get('body')
    if address==51511:
        print(address,body)

#output is nothing. However if I do address!=51511, I get every address with its associated body as an output. Basically implying that value of address does not exist in my xml file. 

所以前面的命令实际上起作用了,我得到了一个空白文件,因为没有一个地址值等于51511(我仍然不知道为什么==51511的输出只给我地址和正文。理论上,由于没有任何东西等于这个值,它应该给我与输入完全相同的输出(包括日期、类型和主题)


Tags: 文件dateisaddress地址typebodyroot
1条回答
网友
1楼 · 发布于 2024-04-19 20:31:15

您可能会注意到,当您打印child.attrib时,您会得到:

{..., 'address': '51511', ...}

因此address属性值是字符串,而不是数字

这就解释了你的结果

相关问题 更多 >