Python覆盖复杂性原则

2024-04-20 04:55:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是Synopsys创建的Coverity,主要包括静态代码分析和动态代码分析工具。我正在对我的代码运行它,结果它生成了一个.xml文件。你知道吗

xml包含了数字串,每个数字串都有自己的含义。我想做一个Python33脚本来打印直接映射到函数复杂性的第七个数字。我可以很好地将它打印到控制台上,但由于我是一名C代码编写人员,而且不仅对Python有偏见,因此我有:

*.xml的行示例:

    <fnmetric>
    <file>FILE1.C</file>
    <fnmet>function1;1;12;10;21;8;9;5;1441.75;0.0557199;;;318</fnmet>
    </fnmetric>
    <fnmetric>
    <file>FILE2.C</file>
    <fnmet>function2;0;0;1;11;8;3;1;184.638;0.0175846;;;352</fnmet>
    </fnmetric>

所以第一个函数的第七个数字是9,第二个是3

到目前为止,我已经:

import fileinput
import glob
import re
import sys

#Read in all files in the directory ending in .xml
files = glob.glob('*.xml')
#search for the line beginning in <fnmet> and ending in </fnmet>
pattern = re.compile(r'<fnmet>\s+;([_A-Z]+)</fnmet>\s+$') #this line is wrong
realstdout = sys.stdout
#create .bak files of the .h files unchanged (backups)
for line in fileinput.input(files, inplace=True, backup='.bak'):
    sys.stdout.write(line)
    m = pattern.match(line)
    #print the 7th #; as  function + complextity through all .xml lines. 
    if m:
        sys.stdout.write('\n <fnmet>\%s</fnmet>\n' % m.group(1)) #this line is wrong
        realstdout.write('%s: %s\n'%(fileinput.filename(),m.group(1))) #this line is wrong

基本上我只是想打印函数名后的第6个数字

比如:

功能1:9 功能2:3

谢谢你的帮助,我的Python太可怕了。你知道吗


Tags: the代码inimportsysline数字files
1条回答
网友
1楼 · 发布于 2024-04-20 04:55:30

看来你的问题出在正则表达式模式上。看看这个例子:

import re

source= '<fnmet>function1;1;12;10;21;8;9;5;1441.75;0.0557199;;;318</fnmet>'

pattern = re.compile(r'(\<fnmet\>)(\S+)(\<\/fnmet\>)')

match = re.findall(pattern, source)
result = match[0][1].split(';')

# result now holds
# ['function1', '1', '12', '10', '21', '8', '9', '5',
#   '1441.75', '0.0557199', '', '', '318']

func_name = 0
pos = 6
print('{}: {}'.format(result[func_name], result[pos]))

这将输出:

function1: 9

我认为使用这个正则表达式和字符串拆分可以很容易地解决您的问题,因为您将能够索引列中的数据。你知道吗

相关问题 更多 >