在正则表达式输出上执行简单的数学 (蟒蛇)

chi*_*ric 7 python regex

是否可以对Python正则表达式的输出执行简单的数学运算?

我有一个大文件,我需要将数字除以")"100之后.例如,我将转换包含)75和的以下行)2:

((words:0.23)75:0.55(morewords:0.1)2:0.55);
Run Code Online (Sandbox Code Playgroud)

)0.75)0.02:

((words:0.23)0.75:0.55(morewords:0.1)0.02:0.55);
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是使用re.sub搜索表达式"\)\d+",但我不知道如何将括号后的整数除以100,或者甚至可以使用re.

有关如何解决这个问题的任何想法?谢谢你的帮助!

Dav*_*son 13

您可以通过提供替换功能来实现:

s = "((words:0.23)75:0.55(morewords:0.1)2:0.55);"

s = re.sub("\)(\d+)", lambda m: ")" + str(float(m.groups()[0]) / 100), s)

print s
# ((words:0.23)0.75:0.55(morewords:0.1)0.02:0.55);
Run Code Online (Sandbox Code Playgroud)

顺便说一下,如果你想用BioPython的Newick树解析器代替它,它看起来像这样:

from Bio import Phylo
# assuming you want to read from a string rather than a file
from StringIO import StringIO

tree = Phylo.read(StringIO(s), "newick")

for c in tree.get_nonterminals():
    if c.confidence != None:
        c.confidence = c.confidence / 100

print tree.format("newick")
Run Code Online (Sandbox Code Playgroud)

(虽然这个特定的操作比正则表达式版本需要更多的行,但是涉及树的其他操作可能会更容易使用它).