finding keywords frequency in a c code using python excluding comments
finding keywords frequency in a c code using python excluding comments
I want to create a program, that can count the frequency of keywords used in a C code, excluding the commented ones or inside printf command.
C
printf
def counting(f, word):
counter = 0
for w in f.split():
if word==w:
counter += 1
return counter
key=open('c_keywords.txt')
keyw=key.read().split()
file=open('a1.cpp').read()
for key in keyw:
x = counting(file,key)
if x != 0:
print (key, ":", x)
Welcome to Stackoverflow. What exactly is your question/problem? You only provided code.
– Bernhard
Aug 28 at 8:46
Possible duplicate of parsing C code using python
– user2653663
Aug 28 at 8:50
2 Answers
2
Here is an example of how to do it with a textfile, you can edit the text.txt and use your C code file instead
with open('text.txt', 'r') as doc:
print('opened txt')
for words in doc:
wordlist = words.split()
for numbers in range(len(wordlist)):
for inner_numbers in range(len(wordlist)):
if inner_numbers != numbers:
if wordlist[numbers] == wordlist[inner_numbers]:
print('word: %s == %s' %(wordlist[numbers], wordlist[inner_numbers]))
Use:
f = open('keywords_c.txt')
count = 0
words =
for x in f:
w = x.split()
for a in w:
words.append(a)
print(words)
cpp = open('Simple_c.cpp')
program =
for y in cpp:
if y.startswith('printf'):
continue
elif y.startswith('//'):
continue
else:
w = y.split()
for b in w:
if any(b in s for s in words):
count +=1
print(count)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
parsing C code using python
– Aran-Fey
Aug 28 at 8:35