最近把很久前的C代码传到Github上的时候,发现全部上百个源文件的代码缩进都变成了8格,而且里面的中文都出现了乱码,所以决定写个程序来批量处理所有文件的格式。这段关于转码的代码可以适用于很多场合,比如Window下默认编码是GBK,而Linux下默认编码是UTF-8,如果两者间传输的文件中出现中文,则需要进行转码。

  • 问题分析

    缩进问题是因为在之前使用vc时没有将制符表设置为4个空格,而Github上的Tab键默认显示八格。中文乱码问题是由于vc++使用的是GBK编码。

  • 解决思路

    1.缩进问题,也就是用空格替换Tab,通过Python程序读取每一行C代码,计算出对应的空格个数,添加到去除首尾空格的源字符串前构成新的一行,然后写入新的文件。

    2.乱码问题,根据Python特性,读取一行字符串后,将在内部自动解码(decode)为Unicode形式,只需要在写入时以utf-8进行编码(encode)并输出就可以实现编码的转换。注意Python输入输出的默认编码为cp936(gbk),要在打开文件时指定写入文件的编码格式。

    3.程序只需接收原始文件夹的路径,通过递归遍历将目录中所有C文件处理后输出到新的文件夹,新文件夹与源文件夹所在目录相同,且包结构完全相同。

import os, codecs

#计算该行应有的缩进空格(考虑Tab和空格混用的情况)
def count_space(st):
count = 0
if st == '\n':
return 0
for ch in st:
if ch == '\t':
count = count + 4
elif ch == ' ':
count = count + 1
else:
break
return count #处理文件:1.将tab转换成相应个数的空格 2.转化为utf-8编码
def process_file(src_path, dest_path):
#设置写入的编码方式为utf-8
#或使用open(dest_path, 'w', encoding = 'utf8')
with open(src_path, 'r') as fr, codecs.open(dest_path, 'w', 'utf-8') as fw:
for line in fr.readlines():
clean_line = line.strip()
n_space = count_space(line)
i = 0
sp = ''
while i < n_space:
sp = sp + ' '
i = i + 1
line = sp + clean_line + '\n'
fw.write(line) #递归遍历整个目录
def travel(src_path, dest_path, item):
if not os.path.isdir(src_path):
if os.path.splitext(src_path)[1] == item:
process_file(src_path, dest_path) #直到遇到相应文件,就进行处理
return if not os.path.isdir(dest_path): #创建对应的目标目录
os.mkdir(dest_path)
#层层深入
for filename in os.listdir(src_path):
travel(os.path.join(src_path, filename), os.path.join(dest_path, filename), item) if __name__ == '__main__':
src_root = 'C:\\Users\\Administrator\\Desktop\\C-Primer-Plus' #接收要处理的文件夹(这里直接指定)
dest_root = src_root + '-new'
item = '.c'
travel(src_root, dest_root, item)

最新文章

  1. C#中ToString()格式详解
  2. Web前端开发笔试&amp;面试_04_20161019MTBS
  3. Span flag详解
  4. Linq101-Miscellaneous
  5. Linq101-Projection
  6. LeetCode227:Basic Calculator II
  7. wsdl生成的客户端
  8. android 关于表格布局的认识
  9. select选中获取索引三种写法
  10. 一文学会Scala
  11. cent os 7 与cent os 6区别
  12. Centos6、7下安装Nginx的两种方法
  13. PHP中对象是按值传递还是按引用传递?
  14. 【洛谷P1637】三元上升子序列
  15. LightOJ 1027 A Dangerous Maze(期望)题解
  16. gravitee-gateway 又一个开源 apigateway
  17. ps叠加模式笔记
  18. 理解SVG的图形填充规则
  19. file_get_contents无法请求https连接的解决方法 php开启curl
  20. mysql 1366的错误 字符集错误解决方案

热门文章

  1. Linux网络管理员:网络概论
  2. 在Spring Boot使用H2内存数据库
  3. js 函数的多图片懒加载(lazy) 带插件版完整解析
  4. c语言----- 冒泡排序 for while do-while 递归练习
  5. Linux打开文件句柄/proc/sys/fs/file-max和ulimit -n的区别
  6. WebStorm 2019 3.3 安装及破解教程附汉化教程
  7. vue父组件向子组件传对象,不实时更新解决
  8. 数制转换itoa atoi int转字符串 字符串转int string转int int转string
  9. Codeforces Round #623 (Div. 2, based on VK Cup 2019-2020 - Elimination Round, Engine) B. Homecoming
  10. dij-spfa乱搞