我有一个输入文本文件,其中有一些C语言代码。我想从该文件中检测出其中包含多少个c数据类型,它将被保存到另一个输出文件中,但首先要显示我的输入文本,然后在此文本下,另一个过滤代码将显示到输出文件中。
在这种情况下,我首先以'a'或追加模式打开了一个文件,但它的工作方向相反。
keyword = ['auto', 'double', 'int', 'struct', 'break', 'else', 'long',
'switch', 'case', 'enum', 'register', 'typedef', 'char',
'extern', 'return', 'union', 'const', 'float', 'short',
'unsigned', 'continue', 'for','signed', 'void', 'default',
'goto', 'sizeof', 'volatile','do', 'if', 'static', 'while']
f_read = open('input.txt', mode='r')
f_write = open('output.txt', 'a')
for i in f_read.read():
f_write.write(i)
f_read.close()
empty = []
for key in keyword:
with open('input.txt', mode='r') as read_fp:
if key in read_fp.read():
if key in empty:
empty[key] += 1
with open('output.txt', 'w') as write_fp:
empty.append(key)
write_fp.write(' \n'.join(empty))
f_write.close()
My input text file all code
then
Data Types-------------Count
int 1
float 3
return 1
进入过滤后,我的输入文件有一些C代码,它会显示1 int,3 浮点数和1种返回数据类型。
谢谢
答案 0 :(得分:0)
如果您需要打印字典(我的应答代码中未使用任何字典)
for k,v in iteritems(mydict):
print ('{}\t{}'.format(k,v))
我对您的问题的解决方案与您尝试的解决方案有很大不同,但是可以满足您的要求(并且如果注释了关键字,则无法处理...)
import re
keyword = ['auto', 'double', 'int', 'struct', 'break', 'else', 'long',
'switch', 'case', 'enum', 'register', 'typedef', 'char',
'extern', 'return', 'union', 'const', 'float', 'short',
'unsigned', 'continue', 'for','signed', 'void', 'default',
'goto', 'sizeof', 'volatile','do', 'if', 'static', 'while']
read_fp = open('input.txt', 'r')
write_fp = open('output.txt', 'w')
content = read_fp.read()
for key in keyword:
# here you have to count each occurrence of your keyword in content, I suggest you use regex :
# the surrounding \W insure that you only match the keywords (e.g int doc_page = 0; shall not match
# 'do'
matches = re.findall('\W{}\W'.format(key), content)
if matches:
write_fp.write ('{}\t{}\n'.format(key, len(matches)))
read_fp.close()
write_fp.close()