我需要计算.c文件中条件(三元)和逗号运算符的出现次数。问题是条件运算符可以是任何类型(它可以是最简单的运算符,它可以是非常长的复合运算符)。这同样适用于逗号运算符。
我绝对不知道该怎么做。我认为使用正则表达式匹配来找到它,但它可能不是最好的选择。你有更好的想法吗?
编辑这里是一些用于分析的输入文件:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/core-input/core-input.html">
<polymer-element name="count-button" extends="button" on-click="increment">
<template>
<content>Increment: </content>
</template>
<script>
Polymer({
counter: 0,
increment: function(e, detail, sender) {
this.counter++;
alert(this.counter);
}
})
</script>
</polymer-element>
输出为:18个三元运算符
答案 0 :(得分:1)
按照您当前的说明,我会编写如下代码:
def match(operator, filename):
with open(filename, "r") as f:
data = f.read()
n = 0
op_len = len(operator)
match = data.find(operator)
while match != -1:
n += 1
data = data[match + op_len:] # cut checked part
match = data.find(operator)
if n > 0:
print """Found {0} "{1}" in {2}""".format(n, operator, filename)
else:
print """No "{0}" in {1}""".format(operator, filename)
if __name__ == "__main__":
operators = ["==", ">", "<", ","] # + any other you want
for op in operator:
match(op, "main.c")