python 提取c文件变量、统计变量出现次数

import os
import re
import sys

#os.chdir(‘F:\PycharmProjects\HelloWord’)

def extract(pattern1, pattern2, str0):
result1 = pattern1.findall(str0)
str = “”
if (result1):
str = result1[0]
else:
result1 = pattern2.findall(str0)
if (result1):
str = result1[0]
return str

def ExtractVariablesFromFile (sourceFileStr, resultFileStr):
sourceFile = open(sourceFileStr)
resultFile = open(resultFileStr, “w”)
pattern1 = re.compile(r’(\w+) =’)
pattern2 = re.compile(r’(\w+);’)
str = “”
for line in sourceFile:
str = extract(pattern1, pattern2, line)
resultFile.write(str)
resultFile.write("\n")
sourceFile.close()
resultFile.close()
def count(f, str):
total = 0
reStr=’ '+str+ ’ ’
pattern1 = re.compile(reStr)
result1 = pattern1.findall(str)
str = “”
if (result1):
str = result1[0]
for line in f:
result1 = pattern1.findall(line.strip())
if(result1):
total += 1
# if str in line:
# total += 1
return total

def VariablesFromFile(sourceFileStr, valuesFileStr, resultFileStr):
sourceFile = open(sourceFileStr)
valuesFile = open(valuesFileStr)
resultFile = open(resultFileStr, “w”)
for line in valuesFile:
if(line.strip() != “”):
sourceFile.seek(0, 0)
line=line.strip()
num = count(sourceFile,line )
resultFile.write(line+" “)
resultFile.write(str(num))
resultFile.write(”\n")
sourceFile.close()
valuesFile.close()
resultFile.close()

sourceFile = sys.argv[1]
valuesFile = sys.argv[2]
resultFile = sys.argv[3]
VariablesFromFile(sourceFile, valuesFile, resultFile)
ExtractVariablesFromFile (‘msq.c’, “msq_value.txt”)

sourceFile = ‘msq.c’

valuesFile= ‘a.txt’

resultFile = “msq_value.txt”

VariablesFromFile(‘foo2.txt’, ‘a.txt’, “countValueNub.txt”)

ExtractVariablesFromFile (‘msq.c’, “msq_value.txt”)

展开阅读全文

没有更多推荐了,返回首页