将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实现对excel文件列表值进行统计的方法
Jul 25 Python
浅谈python中np.array的shape( ,)与( ,1)的区别
Jun 04 Python
pygame游戏之旅 添加游戏介绍
Nov 20 Python
详解Python3 对象组合zip()和回退方式*zip
May 15 Python
Python解析json时提示“string indices must be integers”问题解决方法
Jul 31 Python
django 数据库连接模块解析及简单长连接改造方法
Aug 29 Python
SELENIUM自动化模拟键盘快捷键操作实现解析
Oct 28 Python
python求质数列表的例子
Nov 24 Python
python图形用户接口实例详解
Dec 16 Python
Python字符串的修改方法实例
Dec 19 Python
python模拟预测一下新型冠状病毒肺炎的数据
Feb 01 Python
Keras官方中文文档:性能评估Metrices详解
Jun 15 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
如何用phpmyadmin设置mysql数据库用户的权限
2012/01/09 PHP
PHP写的求多项式导数的函数代码
2012/07/04 PHP
PHP 二维数组根据某个字段排序的具体实现
2014/06/03 PHP
通过JAVASCRIPT读取ASP设定的COOKIE
2007/02/15 Javascript
用JAVASCRIPT如何给<textarea></textarea>赋值
2007/04/20 Javascript
Javascript单元测试框架QUnitjs详细介绍
2014/05/08 Javascript
jQuery截取指定长度字符串代码
2014/08/21 Javascript
图解JavaScript中的this关键字
2020/05/28 Javascript
jQuery EasyUI右键菜单实现关闭标签/选项卡
2016/10/10 Javascript
jQuery时间日期三级联动(推荐)
2016/11/27 Javascript
详解javascript获取url信息的常见方法
2016/12/19 Javascript
NodeJS测试框架mocha入门教程
2017/03/28 NodeJs
浅析Vue实例以及生命周期
2018/08/14 Javascript
layDate日期控件使用方法详解
2018/11/15 Javascript
jQuery中实现text()的方法
2019/04/04 jQuery
laravel实现中文和英语互相切换的例子
2019/09/30 Javascript
vue data引入本地图片的两种方式小结
2019/11/13 Javascript
js Math数学简单使用操作示例
2020/03/13 Javascript
nodeJs项目在阿里云的简单部署
2020/11/27 NodeJs
[59:30]完美世界DOTA2联赛PWL S3 access vs LBZS 第二场 12.20
2020/12/23 DOTA
Python中turtle作图示例
2017/11/15 Python
Python自然语言处理之词干,词形与最大匹配算法代码详解
2017/11/16 Python
Python如何生成树形图案
2018/01/03 Python
TensorFlow如何实现反向传播
2018/02/06 Python
Django Admin实现三级联动的示例代码(省市区)
2018/06/22 Python
tensorflow学习教程之文本分类详析
2018/08/07 Python
解决pycharm运行程序出现卡住scanning files to index索引的问题
2019/06/27 Python
python中property属性的介绍及其应用详解
2019/08/29 Python
Centos7 下安装最新的python3.8
2019/10/28 Python
python列表切片和嵌套列表取值操作详解
2020/02/27 Python
写好自荐信要注意的问题
2013/11/10 职场文书
运动会入场解说词300字
2014/01/25 职场文书
社区志愿者服务心得体会
2016/01/22 职场文书
Mysql实现主从配置和多主多从配置
2021/06/02 MySQL
Redis入门基础常用操作命令整理
2022/06/01 Redis
ant design vue的form表单取值方法
2022/06/01 Vue.js