【问题标题】:How to put text using BeautifulSoup如何使用 BeautifulSoup 放置文本
【发布时间】:2021-01-10 01:26:36
【问题描述】:

我正在解析.xml 文件。我需要转换为.csv 个人文件:names.txt

例如:

names.txt:

anna
james
miray
vill

XML file:

<data>
    <AAA>
        <CCC>
            <person>name1</person>
        </CCC>
        <CCC>  
            <person>name2</person>
        </CCC>
        <CCC>
            <person>name3</person>
        </CCC>
    </AAA>
</data>

【问题讨论】:

  • stackoverflow 上的第一个链接解释了从 .xml.csv 的转换。在您的情况下,.csv 只有 1 列。

标签: python xml beautifulsoup


【解决方案1】:

你可以用这个:

from bs4 import BeautifulSoup

example_string = '<data><AAA><CCC><person>name1</person></CCC><CCC><person>name2</person></CCC><CCC><person>name3</person></CCC></AAA></data>'

# Here I hard code the list of names. My assumption is you already know how
# to read the names from names.txt into a list.
names = ['anna', 'james', 'miray']

# Parse the XML into a BeautifulSoup
soup = BeautifulSoup(example_string, 'lxml-xml')

# Replace the content of each 'person' tag
for name, item in zip(names, soup.find_all('person')):
    item.string = name

# Pretty-print the XML after modifications
print(soup.prettify())

这将有以下输出:

<?xml version="1.0" encoding="utf-8"?>
<data>
 <AAA>
  <CCC>
   <person>
    anna
   </person>
  </CCC>
  <CCC>
   <person>
    james
   </person>
  </CCC>
  <CCC>
   <person>
    miray
   </person>
  </CCC>
 </AAA>
</data>

【讨论】:

  • 此答案在编写时正确回答了问题。从那以后,这个问题被更新为要求一些非常不同的东西。请不要对我的回答投反对票。
  • @villwocki 为什么在您的问题被编辑后接受我的回答?编辑您的问题的人已对其进行了足够的更改,以至于我的答案不再回答新版本的问题。
猜你喜欢
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 2012-11-13
  • 1970-01-01
相关资源
最近更新 更多