在python中用相同的字符串替换前导文本字符串

时间:2013-12-24 10:10:03

标签: python xml

我在xml文件中有以下标记

  带有首字母的

& \ hbox {(1b)}} $$   条件< 2inline-formula> $ x(0)$,其中下标   < 3inline-formula> $ p $表示   '厂'; < 4inline-formula> $ x_ {p}(t)\ in \ Re ^ {n} $ is   状态,< 5inline-formula> $ y_ {p}(t)\ in \ Re ^ {q} $是   输出,< 6inline-formula> $ u_ {p}(t)\ in \ Re ^ {m} $是   输入; < 7inline-式GT;

我想将所有以数字开头的内联公式替换为<inline-formula>,但我无法给出搜索内联公式的条件,这些公式与数字相关,因此对此有任何帮助..谢谢预先

1 个答案:

答案 0 :(得分:0)

您必须使用正则表达式(re模块)来检测“内联公式”(\d+inline-formula)之前的一个或多个数字。

就像这样:

>>> import re
>>> original = "&\hbox{(1b)}}$$ with the initial condition <2inline-formula>$x(0)$, where the subscript <3inline-formula>$p$ means 'plant’; <4inline-formula>$x_{p}(t) \in \Re^{n}$ is the state, <5inline-formula>$y_{p}(t)\in\Re^{q}$ is the output, and <6inline-formula>$u_{p}(t)\in\Re^{m}$ is the input; <7inline-formula>"
>>> new = re.sub(r"<\d+inline-formula>", "<inline-formula>", original)
>>> print new
"&\\hbox{(1b)}}$$ with the initial condition <inline-formula>$x(0)$, where the subscript <inline-formula>$p$ means 'plant\xe2\x80\x99; <inline-formula>$x_{p}(t) \\in \\Re^{n}$ is the state, <inline-formula>$y_{p}(t)\\in\\Re^{q}$ is the output, and <inline-formula>$u_{p}(t)\\in\\Re^{m}$ is the input; <inline-formula>"
>>>