将html页面中的“\n”替换为python LXML中的空格
我有一个不清楚的xml,并使用python lxml模块处理它。我想用将html页面中的“\n”替换为python LXML中的空格,python,lxml,Python,Lxml,我有一个不清楚的xml,并使用python lxml模块处理它。我想用空格替换内容中的所有\n,在进行任何处理之前,如何对所有元素的文本执行此操作 编辑 我的xml示例: <root> <a> dsdfs\n dsf\n sdf\n</a> <bds> <d>sdf\n\n\n\n\n\n</d> <d>sdf\n\n\nsdf\nsdf\n\n</d>
空格替换内容中的所有\n
,在进行任何处理之前,如何对所有元素的文本执行此操作
编辑
我的xml示例:
<root>
<a> dsdfs\n dsf\n sdf\n</a>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
....
....
....
....
</root>
您尝试过的代码到底是什么?字符串对于初学者来说是不可变的,Python中没有“replaceall”方法
for i in root_elem.itertext():
j = i.replace('\n',' ')
print(j+'\n') # or some fp.write call to a new file
下面的代码将xml解析为字符串,然后将\n
替换为空格
,然后写入新的xml文件。您可以在这两者之间执行其他处理,具体取决于您想要执行的操作
from lxml import etree
tree = etree.parse('some.xml')
root = tree.getroot()
# Get the whole XML content as string
xml_in_str = etree.tostring(root)
# Replace all \n with space
new_xml_data = xml_in_str.replace(r'\n', ' ')
# Do the processing with the new_xml_data string which is formatted
# Maybe also write to a new XML file, without the \n
with open('newxml.xml', 'w') as f:
f.write(new_xml_data)
some.xml
看起来像:
<root>
<a> dsdfs\n dsf\n sdf\n</a>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
<bds>
<d>sdf\n\n\n\n\n\n</d>
<d>sdf\n\n\nsdf\nsdf\n\n</d>
</bds>
</root>
<root>
<a> dsdfs dsf sdf </a>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
</root>
你能举一个你不清楚的xml的例子吗?正则表达式模块是你想要的吗<代码>导入re;re.sub(i,'\n','')
我想在此更改后使用lxml进行处理。我不想更改最终文本,但我不想更改元素文本我想在此更改后使用lxml处理此代码更改结果,但我想更改元素类的文本
<root>
<a> dsdfs dsf sdf </a>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
<bds>
<d>sdf </d>
<d>sdf sdf sdf </d>
</bds>
</root>