【问题标题】:change value of tag respecting conditions根据条件更改标签的值
【发布时间】:2020-06-07 22:45:06
【问题描述】:

我想读取一个 csv 文件。

第一列指tag source,第二列指value source,第三列指target value要改。最后一列指的是 tag name 已更改。

请问我该如何动态完成?

 Types1, Init, INITIAL, Type1

 Types1, inits, INITIAL, Type1

 Types2, ANNULE, delayed, Type2

 Types3, Topp, high, Type3

 Types3, best, TOP, Type3

输入样本

<data>
  <db1>
    <Types1> Init </Types1>
    <Types1> inits </Types1>
    <Types3> best </Types3>
  </db1>
  <db1>
    <Types2> ANNULE </Types2>
    <Types3> Topp </Types3>
    <Types3> best </Types3>
  </db1>   
<data>

预期输出

<data>
  <db1>
    <Type1> INITIAL </Type1>
    <Type1> INITIAL </Type1>
    <Type3> TOP </Type3>
  </db1>
  <db1>
    <Type2> delayed </Type2>
    <Type3> high </Type3>
    <Type3> TOP </Type3>
  </db1>   

【问题讨论】:

  • 到目前为止你尝试了什么?
  • @ZarakiKenpachi 我通过手动访问标签而不通过 csv 文件来做到这一点。
  • 你输入的数据、发布的几行和预期的输出是什么?
  • @ZarakiKenpachi 感谢您的回复。原帖已编辑
  • 输入输出都是json文件?

标签: python python-3.x pandas xml-parsing


【解决方案1】:

对于如下的 csv 数据:

你需要使用pandas来管理csv和ElementTree来管理xml文件。

import xml.etree.ElementTree
import pandas as pd

df = pd.read_csv('data.csv')
root = xml.etree.ElementTree.parse('data.xml')

for tag in df['tag'].unique():
    for item in root.iter(tag):
        text = item.text.strip()
        data_row = df[(df['tag']==tag) & (df['old']==text)]
        item.text = data_row['new'].values[0]

root.write('file_new.xml')

输出:

<data>
  <db1>
    <Types1>INITIAL</Types1>
    <Types1>INITIAL</Types1>
    <Types3> best </Types3>
  </db1>
  <db1>
    <Types2>delayed</Types2>
    <Types3> Topp </Types3>
    <Types3> best </Types3>
  </db1>   
</data>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2022-01-25
    • 1970-01-01
    • 2014-10-09
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多