Skip to content

Instantly share code, notes, and snippets.

@hjeffrey
Created February 24, 2021 07:31
Show Gist options
  • Save hjeffrey/60dd20872bc860632b0ab25a14db2ca9 to your computer and use it in GitHub Desktop.
Save hjeffrey/60dd20872bc860632b0ab25a14db2ca9 to your computer and use it in GitHub Desktop.
iOS项目输出纯代码的word文档
#!/usr/bin/python
# -*- coding:utf-8 -*-
#
# iOS项目输出纯代码的word文档
# .m 与 .swift 文件
# 去掉空行
# 去掉注释,包括/** ... */,// 和 #pragma
# 去掉引用头文件
import os
import sys
import glob
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH,WD_LINE_SPACING
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.ns import qn
def init():
global document
document = Document()
# style
style = document.styles['Normal']
font = style.font
font.name = u'宋体'
font.size = Pt(10.5)
# code
global paragraph
paragraph = document.add_paragraph()
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
def writeContent2Docx(fileName):
f = open(fileName, 'r')
contents = f.readlines()
print(fileName)
is_commit = False
if len(contents) > 0:
for line in contents:
if len(line) > 0:
newLine = line.strip()
if len(newLine)>0:
if newLine.startswith('/**'):
is_commit = True
if is_commit and newLine.endswith('**/'):
is_commit = False
continue
if is_commit or newLine.startswith('//') or newLine.startswith('#import ') or newLine.startswith('#include ') or newLine.startswith('import ') or newLine.startswith('#pragma '):
pass
else:
lineCommitIndex = line.find('//')
if lineCommitIndex >0:
addLine(line[:lineCommitIndex])
else:
addLine(line)
f.close()
def addLine(line):
run = paragraph.add_run(line.decode('utf-8'))
run.font.name = u'宋体'
run.font.size = Pt(10.5)
run.font.color.rgb = RGBColor(0,0,0) #设置颜色为黑色
run._element.rPr.rFonts.set(qn('w:eastAsia'), run.font.name)
def saveDocx():
# 保存
if os.path.isfile(codePath):
newPath = os.path.dirname(codePath)+"/code.docx"
else:
newPath = codePath+"/code.docx"
document.save(newPath)
def checkFileOfPath(path):
if os.path.isfile(path):
if path.endswith(".m") or path.endswith(".mm") or path.endswith(".swift"):
writeContent2Docx(path)
elif os.path.isdir(path):
filePaths = os.listdir(path)
for file in filePaths:
checkFileOfPath(path+"/"+file)
else:
print("目录不存在")
if __name__ == '__main__':
global codePath
codePath = sys.argv[1].decode('utf-8')
init()
checkFileOfPath(codePath)
saveDocx()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment