将python代码和注释分离的方法


Posted in Python onApril 21, 2018

python的注释方式和C语言、C++、java有所不同

python语言中,使用‘#' 来进行注释,其次还有使用 三个引号来进行注释

本文的程序将把 python 中 使用‘#' 号 好 三个引号的注释分离出来, 当然也能再次合并回去

有需求的小伙伴可以来围观了

#!/usr/bin/python
#coding=utf-8
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Comment_Filter:
	#初始化参数
	def __init__(self):
		self.file=None
		self.commentfile=None
		self.noncommentline=None
		self.resotrefile=None
		self.Commentline=[]
		self.NonCommentline=[]
		self.globalcomment=0
	#判断是不是注释行
	def is_Comment_Line(self,line,i):
		if i > 2 and line.startswith("#"):
			return 1
		if line.startswith("'''") and self.globalcomment==1:
			self.globalcomment=0
			return 1
		if line.startswith("'''") and self.globalcomment==0:
			self.globalcomment=1
			return 1
		return self.globalcomment
	#保存注释行
	def save_Comment_Line(self,line,i):
		self.Commentline.append({"line":line, "line_num":i})
	#保存代码行
	def save_NonComment_Line(self,line,i):
		self.NonCommentline.append({"line":line, "line_num":i})
	#恢复分离的文件
	def restore_Org_File(self):
		filename="output/"+self.filename+"_org.txt"
		self.resotrefile=open(filename, "w+")
		for i in range(1,len(self.Commentline)+len(self.NonCommentline)+1):
			for commentline in self.Commentline:
				if int(commentline['line_num'])==i:
					self.resotrefile.write(commentline['line'])
			for noncommentline in self.NonCommentline:
				if int(noncommentline['line_num'])==i:
					self.resotrefile.write(noncommentline['line'])
		print "已输出到%s" % filename
		self.resotrefile.close()
	#主运行函数
	def run(self):
		if not os.path.exists("output"):
			os.mkdir("output")
		print "请输入要处理的文件名"
		input_file_name=raw_input()
		while len(input_file_name)>1:
			print "处理文件为%s" % input_file_name
			self.file=open(input_file_name)
			self.filename=input_file_name.split(".")[1]
			commentfilename="output/"+input_file_name.split(".")[1]+"_comment.txt"
			self.commentfile=open(commentfilename,"w+")
			noncommentlinename="output/"+input_file_name.split(".")[1]+"_code.txt"
			self.noncommentline=open(noncommentlinename,"w+")
			i = 0
			while self.file != None:
				line = self.file.readline()
				i +=1
				if not line:
					print "文件已读完"
					print "以下是注释内容"
					for commentline in self.Commentline:
						print "第%d行: %s" % (commentline['line_num'],commentline['line'])
						self.commentfile.write(commentline['line'])
					
					print "以下是代码内容"
					for noncommentline in self.NonCommentline:
						print "第%d行: %s" % (noncommentline['line_num'],noncommentline['line'])
						self.noncommentline.write(noncommentline['line'])
					restore=raw_input("是否恢复成原文件:")
					if restore == 'Y':
						self.restore_Org_File()
					self.commentfile.close()
					self.noncommentline.close()
					break
				if self.is_Comment_Line(line,i):
					self.save_Comment_Line(line,i)
				else:
					self.save_NonComment_Line(line,i)
			print "请输入文件名"
			input_file_name=raw_input('if quit,please input Q:')
			if input_file_name == 'Q':
				break
if __name__ == '__main__':
	print '''
			***************************************** 
			**  Welcome to Spider of baidutieba ** 
			**   Created on 2017-05-03     ** 
			**   @author: Jimy _Fengqi     ** 
			*****************************************
	'''
	my_file_divide_filter=Comment_Filter()
	my_file_divide_filter.run()

本程序已知问题, 不能处理 空格之后在以‘#' 开头的注释,所有的注释行,必须是顶格写的

以后有时间的话,再重新写一版完整的吧

以上这篇将python代码和注释分离的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python的Django框架中使用通用视图的方法
Jul 21 Python
Python在Windows和在Linux下调用动态链接库的教程
Aug 18 Python
Python使用min、max函数查找二维数据矩阵中最小、最大值的方法
May 15 Python
python利用smtplib实现QQ邮箱发送邮件
May 20 Python
Tensorflow实现卷积神经网络的详细代码
May 24 Python
python判断一个对象是否可迭代的例子
Jul 22 Python
python列表推导和生成器表达式知识点总结
Jan 10 Python
opencv python在视屏上截图功能的实现
Mar 05 Python
设置jupyter中DataFrame的显示限制方式
Apr 12 Python
让Django的BooleanField支持字符串形式的输入方式
May 20 Python
python判断字符串以什么结尾的实例方法
Sep 18 Python
使用Python将xmind脑图转成excel用例的实现代码(一)
Oct 12 Python
Python基于百度AI的文字识别的示例
Apr 21 #Python
python实现随机调用一个浏览器打开网页
Apr 21 #Python
python爬虫 使用真实浏览器打开网页的两种方法总结
Apr 21 #Python
Python针对给定字符串求解所有子序列是否为回文序列的方法
Apr 21 #Python
Django项目实战之用户头像上传与访问的示例
Apr 21 #Python
基于Python 装饰器装饰类中的方法实例
Apr 21 #Python
使用python装饰器计算函数运行时间的实例
Apr 21 #Python
You might like
php 引用(&)详解
2009/11/20 PHP
深入PHP magic quotes的详解
2013/06/17 PHP
PHP针对多用户实现更换头像功能
2016/09/04 PHP
js+CSS 图片等比缩小并垂直居中实现代码
2008/12/01 Javascript
JavaScript 嵌套函数指向this对象错误的解决方法
2010/03/15 Javascript
简单的jquery拖拽排序效果实现代码
2011/09/20 Javascript
基于JQuery的购物车添加删除以及结算功能示例
2017/03/08 Javascript
如何使用vuejs实现更好的Form validation?
2017/04/07 Javascript
详解如何让Express支持async/await
2017/10/09 Javascript
微信小程序获取手机网络状态的方法【附源码下载】
2017/12/08 Javascript
node.js部署之启动后台运行forever的方法
2018/05/23 Javascript
使用layer弹窗和layui表单实现新增功能
2018/08/09 Javascript
vue中eslintrc.js配置最详细介绍
2018/12/21 Javascript
JS尾递归的实现方法及代码优化技巧
2019/01/19 Javascript
JavaScript中filter的用法实例分析
2019/02/27 Javascript
webpack4实现不同的导出类型
2019/04/09 Javascript
jquery实现的放大镜效果示例
2020/02/24 jQuery
js基于canvas实现时钟组件
2021/02/07 Javascript
wxpython 学习笔记 第一天
2009/02/09 Python
python用ConfigObj读写配置文件的实现代码
2013/03/04 Python
python实现雪花飘落效果实例讲解
2019/06/18 Python
Django用户认证系统 组与权限解析
2019/08/02 Python
numpy.ndarray 实现对特定行或列取值
2019/12/05 Python
python3检查字典传入函数键是否齐全的实例
2020/06/05 Python
个性化皮包、小袋、生活配件:Mon Purse
2019/03/26 全球购物
机电专业个人自荐信格式模板
2013/09/23 职场文书
《会变的花树叶》教学反思
2014/02/10 职场文书
《李时珍夜宿古寺》教学反思
2014/04/09 职场文书
中学优秀班主任事迹材料
2014/05/01 职场文书
专项法律服务方案
2014/06/11 职场文书
小学教师师德整改措施
2014/09/29 职场文书
检讨书模板
2015/01/29 职场文书
2015年村计划生育工作总结
2015/04/28 职场文书
联谊会开场白
2015/06/01 职场文书
2016年万圣节家长开放日活动总结
2016/04/05 职场文书
Python中文纠错的简单实现
2021/07/07 Python