账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    XML文件提取标签,或者增加子标签和其他子标签数量一致
    • 2020-01-01 00:00
    • 11
    52
    0

    所处理的XML文件内容如下:

    <incollection>
    <author>Philippe Balbiani</author>
    <author>Valentin Goranko</author>
    <author>Ruaan Kellerman</author>
    <author>Dimiter Vakarelov</author>
    <booktitle>Handbook of Spatial Logics</booktitle>
    </incollection>
    <incollection>
    <author>Jochen Renz</author>
    <author>Bernhard Nebel</author>
    <booktitle>Handbook of AI</booktitle>
    </incollection>
    ...
    格式内容如上所示,提取<author>标签内容和<booktitle>标签内容,它们都在<incollection>标签里,遍历每个<incollection>标签,并让多个author标签内容与一个booktitle标签内容形成对应元组

    达到理想结果为:

    ('Philippe Balbiani', 'Handbook of Spatial Logics')
    ('Valentin Goranko', 'Handbook of Spatial Logics')
    ('Ruaan Kellerman', 'Handbook of Spatial Logics')
    ('Dimiter Vakarelov', 'Handbook of Spatial Logics')
    ('Jochen Renz', 'Handbook of AI')
    ('Bernhard Nebel', 'Handbook of AI')

    请给出实现代码

    或者能把每个<incollection>标签里的<booktitle>标签增加到和<author>标签数量一致,理想结果:
    <incollection>
    <author>Philippe Balbiani</author>
    <author>Valentin Goranko</author>
    <author>Ruaan Kellerman</author>
    <author>Dimiter Vakarelov</author>
    <booktitle>Handbook of Spatial Logics</booktitle>
    <booktitle>Handbook of Spatial Logics</booktitle>
    <booktitle>Handbook of Spatial Logics</booktitle>
    <booktitle>Handbook of Spatial Logics</booktitle>
    </incollection>
    <incollection>
    <author>Jochen Renz</author>
    <author>Bernhard Nebel</author>
    <booktitle>Handbook of AI</booktitle>
    <booktitle>Handbook of AI</booktitle>
    </incollection>

    请给出实现代码

    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 在XML文件中,标签名是唯一的。如果你想提取某个特定标签的所有内容,你可以使用XPath查询语言。XPath是一种用来在XML文档中查找、选择和提取信息的语言。

      以下是一个使用XPath查询提取特定标签内容的Python代码示例:

      ```python import xml.etree.ElementTree as ET

      解析XML文件

      tree = ET.parse('your_file.xml') root = tree.getroot()

      使用XPath查询提取特定标签内容

      result = root.find('your_tag').text

      打印提取的内容

      print(result) ```

      在这个示例中,你需要将'your_file.xml'和'your_tag'替换为你的XML文件名和你要提取标签的名称。

      如果你想增加子标签数量一致,你可以使用递归来实现。以下是一个示例:

      ```python import xml.etree.ElementTree as ET

      解析XML文件

      tree = ET.parse('your_file.xml') root = tree.getroot()

      使用递归来提取特定标签及其子标签

      def extract_content(element, depth=0): # 检查元素是否是你要提取的标签 if element.tag == 'your_tag': # 如果是,返回该标签的内容 return element.text # 否则,递归地提取其子标签 else: # 如果是子标签,递归地提取子标签及其子标签 return extract_content(element, depth + 1)

      使用递归来提取特定标签及其子标签

      result = extract_content(root)

      打印提取的内容

      print(result) ```

      在这个示例中,你需要将'your_file.xml'和'your_tag'替换为你的XML文件名和你要提取标签的名称,以及递归的深度。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部