gpt4 book ai didi

python - 对正则表达式输出执行简单的数学运算? (Python)

转载 作者:太空狗 更新时间:2023-10-29 21:24:44 32 4
gpt4 key购买 nike

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

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

((words:0.23)75:0.55(morewords:0.1)2:0.55);

)0.75)0.02:

((words:0.23)0.75:0.55(morewords:0.1)0.02:0.55);

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

关于如何解决这个问题有什么想法吗?感谢您的帮助!

最佳答案

你可以通过提供一个函数作为替代来做到这一点:

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);

顺便说一句,如果您想使用 BioPython's Newick tree parser 来完成它相反,它看起来像这样:

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")

(虽然此特定操作比正则表达式版本需要更多行,但其他涉及树的操作可能会更容易)。

关于python - 对正则表达式输出执行简单的数学运算? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14177592/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com