用python将c内置数据类型检测到输入文本文件中

2024-05-06 07:07:26 发布

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

我有一个输入文本文件有一些c语言代码。我想从该文件中检测有多少c数据类型包含在那里,它将被保存到另一个输出文件中,但首先要显示我的输入文本,然后在此文本下,我的另一个过滤代码将显示到输出文件中。你知道吗

在本例中,首先我用“a”或append模式打开了一个文件,但它的工作方式相反。你知道吗

我的代码

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

into my input file has some c code after filtering it'll show 1 int, 3 float and 1 return data types.

谢谢


Tags: 文件key代码intxtforreadinput
1条回答
网友
1楼 · 发布于 2024-05-06 07:07:26

如果你需要打印口述(我的答案代码中没有使用任何口述)

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()

相关问题 更多 >