在python lxml prettyprint中更改标签间距 - python

我有一个小的脚本,可以创建xml文档,并使用prettyprint=true可以创建格式正确的xml文档。但是,制表符的缩进是2个空格,我想知道是否有办法将其更改为4个空格(我认为4个空格看起来更好)。有没有简单的方法来实现这一目标?

程式码片段:

doc = lxml.etree.SubElement(root, 'dependencies')
for depen in dependency_list:
    dependency = lxml.etree.SubElement(doc, 'dependency')
    lxml.etree.SubElement(dependency, 'groupId').text = depen.group_id
    lxml.etree.SubElement(dependency, 'artifactId').text = depen.artifact_id
    lxml.etree.SubElement(dependency, 'version').text = depen.version
    if depen.scope == 'provided' or depen.scope == 'test':
        lxml.etree.SubElement(dependency, 'scope').text = depen.scope
    exclusions = lxml.etree.SubElement(dependency, 'exclusions')
    exclusion = lxml.etree.SubElement(exclusions, 'exclusion')
    lxml.etree.SubElement(exclusion, 'groupId').text = '*'
    lxml.etree.SubElement(exclusion, 'artifactId').text = '*'
tree.write('explicit-pom.xml' , pretty_print=True)

python大神给出的解决方案

python lxml API似乎无法做到这一点。

制表符间距的可能解决方案是:

def prettyPrint(someRootNode):
    lines = lxml.etree.tostring(someRootNode, encoding="utf-8", pretty_print=True).decode("utf-8").split("\n")
    for i in range(len(lines)):
        line = lines[i]
        outLine = ""
        for j in range(0, len(line), 2):
            if line[j:j + 2] == "  ":
                outLine += "\t"
            else:
                outLine += line[j:]
                break
        lines[i] = outLine
    return "\n".join(lines)

请注意,这不是很有效。只有在lxml C代码中本地实现此功能时,才能实现高效率。

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

Python:同时在for循环中添加到列表列表 - python

我想用for循环外的0索引值创建一个新列表,然后使用for循环添加到相同的列表。我的玩具示例是:import random data = ['t1', 't2', 't3'] masterlist = [['col1', 'animal1', 'an…

在Python中迭代OrderedDict - python

我有以下OrderedDict:OrderedDict([('r', 1), ('s', 1), ('a', 1), ('n', 1), ('y', 1)]) 实际上,这表示单词中字母的出现频率。第一步-我将使用最后两个元素来创建一个这样的联合元组; pair…

如何在Matplotlib条形图后面绘制网格线 - python

x = ['01-02', '02-02', '03-02', '04-02', '05-02'] y = [2, 2, 3, 7, 2] fig, ax = plt.subplots(1, 1) ax.bar(range(len(y)), y, width=…

在独立的scrapy脚本中使用自定义中间件 - python

我正在编写一个实现自定义下载器中间件的独立抓取脚本(update.py)。该脚本当前使用记录在here和here中的CrawlerProcess()API。看起来像这样:from scrapy.crawler import CrawlerProcess import scrapy class CustomMiddleware(object): .... cu…