不能在lxml etree中使用translate()方法的xpath。

huangapple go评论61阅读模式
英文:

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 = &#39;&#39;&#39;&lt;root&gt;
    &lt;a&gt;A TEXT CONTENT&lt;/a&gt;
&lt;/root&gt;&#39;&#39;&#39;

root = etree.fromstring(xml)
element = root.xpath(&#39;translate(./a/text(), &quot;A&quot;, &quot;a&quot;)&#39;)
print(element)

Result

a TEXT CONTENT

You can also specify more translation rules

element = root.xpath(&#39;translate(./a/text(), &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;, &quot;abcdefghijklmnopqrstuvwxyz&quot;)&#39;)

Result

a text content

huangapple
  • 本文由 发表于 2023年5月11日 12:54:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定