Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对正则表达式输出执行简单数学运算?(Python)_Python_Regex - Fatal编程技术网

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

对正则表达式输出执行简单数学运算?(Python),python,regex,Python,Regex,可以对Python正则表达式的输出执行简单的数学运算吗 我有一个大文件,需要将“后面的数字除以100。例如,我将转换包含)75和)2的以下行: 到)0.75和)0.02: ((words:0.23)0.75:0.55(morewords:0.1)0.02:0.55); 我的第一个想法是使用搜索表达式re.sub,“\)\d+”,但我不知道如何将括号后的整数除以100,或者使用re是否可以 如何解决这个问题有什么想法吗?谢谢你的帮助 re.sub的替换表达式可以是函数。编写一个函数,该函数接受匹

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

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

)0.75
)0.02

((words:0.23)0.75:0.55(morewords:0.1)0.02:0.55);
我的第一个想法是使用搜索表达式
re.sub
“\)\d+”
,但我不知道如何将括号后的整数除以100,或者使用
re
是否可以


如何解决这个问题有什么想法吗?谢谢你的帮助

re.sub的替换表达式可以是函数。编写一个函数,该函数接受匹配的文本,将其转换为数字,将其除以100,然后返回结果的字符串形式。

您可以提供一个函数作为替换:

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);
顺便说一句,如果您想使用,它将如下所示:

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

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

您是否尝试过将字符串转换为整数?正则表达式用于文本操作。要实现这一点,我看不到将字符串转换为整数并将其除以100的任何转义。顺便说一句,这看起来像是Newick格式(除了在Newick格式中,您通常不会对单个节点(如
words
morewwords
)有引导信心)。使用Newick解析器(如)而不是正则表达式,您可能更容易执行其他操作。是的,您是对的——我将Newick树中的引导值除以100。谢谢你的提示。
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")