用python将项目中的所有代码(或txt)合并在一个文件中
设计模式开卷考试给的例子代码都是一个类一个java,实在太恶心了,所以写了一个python脚本.
import os
fileansdir=r'C:\Users\tonyson_in_the_rain\Desktop\笔记\JAVA代码\设计模式'
主要用的os库
API总结:
- files=listdir(path) 显示当前目录的所有文件名和目录名
- endswith() 选择扩展名
- windows的路径只需要前面加一个r即可在python程序中使用
- 把合并的文件在当前目录保存,也可以改成某一目录保存,但是要注意名字
combine函数是一个子过程,可以把dirpath目录下的所有文件合并为一个文件
def combine(dirPath,filename):
files=os.listdir(dirPath)
res=""
i = 0
for file in files:
if file.endswith(".java"):
i+=1
title=file
with open(dirPath+'\\'+file,"r")as file:
content=file.read()
file.close()
res+='\n\n'
res+='#### '+title
res+='\n\n'
res+='```\n'
res+=content
res+='\n```\n'
with open(dirPath+'\\'+filename+'.txt','w')as outFile:
outFile.write(res)
outFile.close()
然后遍历各个文件夹分别跑一遍子过程即可
import os
def EnumPathFiles(path, callback):
ii=0
if not os.path.isdir(path):
print('Error:"',path,'" is not a directory or does not exist.')
return
list_dirs = os.walk(path)
for root, dirs, files in list_dirs:
for d in dirs:
EnumPathFiles(os.path.join(root, d), callback)
dirc=path+'\\'+d
print(dirc)
if(dirc.endswith('memento')):
continue
ii+=1
name=d
combine(dirc,name)
def callback1(path, filename):
print(path+'\\'+filename)
EnumPathFiles(r'C:\Users\tonyson_in_the_rain\Desktop\大三上学习\设计模式\设计模式2018(张欣佳)', callback1)
这里会报一个错误,因为子目录对不上号的原因,不过在这之前有用的目录我们已经跑过了,所以不用管了.
合成的md文件如下:不过是按照类名字典序排的,需要手动调整顺序
Apple.java
public class Apple implements Product
{
public void accept(Visitor visitor)
{
visitor.visit(this);
}
}
Book.java
public class Book implements Product
{
public void accept(Visitor visitor)
{
visitor.visit(this);
}
}
BuyBasket.java
import java.util.*;
public class BuyBasket
{
private ArrayList list=new ArrayList();
public void accept(Visitor visitor)
{
Iterator i=list.iterator();
while(i.hasNext())
{
((Product)i.next()).accept(visitor);
}
}
public void addProduct(Product product)
{
list.add(product);
}
public void removeProduct(Product product)
{
list.remove(product);
}
}
Client.java
public class Client
{
public static void main(String a[])
{
Product b1=new Book();
Product b2=new Book();
Product a1=new Apple();
Visitor visitor;
BuyBasket basket=new BuyBasket();
basket.addProduct(b1);
basket.addProduct(b2);
basket.addProduct(a1);
visitor=(Visitor)XMLUtil.getBean();
visitor.setName("张三");
basket.accept(visitor);
}
}
Customer.java
public class Customer extends Visitor
{
public void visit(Apple apple)
{
System.out.println("顾客" + name + "选苹果。");
}
public void visit(Book book)
{
System.out.println("顾客" + name + "买书。");
}
}
Product.java
public interface Product
{
void accept(Visitor visitor);
}
Saler.java
public class Saler extends Visitor
{
public void visit(Apple apple)
{
System.out.println("收银员" + name + "给苹果过秤,然后计算其价格。");
}
public void visit(Book book)
{
System.out.println("收银员" + name + "直接计算书的价格。");
}
}
Visitor.java
public abstract class Visitor
{
protected String name;
public void setName(String name)
{
this.name=name;
}
public abstract void visit(Apple apple);
public abstract void visit(Book book);
}