英文:
Can not use translate() method in xpath with lxml etree
问题
我想使用Python中的lxml库来将文本转换为小写。我的代码如下:
r = element.xpath('./a/translate(text(), "A", "a")')
但是它给我一个异常:
lxml.etree.XPathEvalError: Invalid expression
我想只使用xpath来做到这一点(而不写Python代码)。请给我一个解决方案。谢谢。
英文:
I want to use translate to lower my text with lxml library in Python. My code is as below
r = element.xpath('./a/translate(text(), "A", "a")')
But it give me an exception:
lxml.etree.XPathEvalError: Invalid expression
I'd like to do this with xpath only (without writing code in Python). Please give me a solution. Thanks
答案1
得分: 0
以下是代码的翻译部分:
from lxml import etree
xml = '''<root>
<a>文本内容</a>
</root>'''
root = etree.fromstring(xml)
element = root.xpath('translate(./a/text(), "文本", "text")')
print(element)
结果:
text content
你还可以指定更多的翻译规则:
element = root.xpath('translate(./a/text(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")')
结果:
text content
英文:
You may try following code by wrapping up the translate outside
from lxml import etree
xml = '''<root>
<a>A TEXT CONTENT</a>
</root>'''
root = etree.fromstring(xml)
element = root.xpath('translate(./a/text(), "A", "a")')
print(element)
Result
a TEXT CONTENT
You can also specify more translation rules
element = root.xpath('translate(./a/text(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")')
Result
a text content
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论