目的
项目中,遇到需要读取python list 格式的txt, 需要将Python的list 字符串中的元素及sub list提取出来。
txt 格式的文件内容
[[None, 0, 0], [None, 0, 0], [None, 0, 0], [[[622, 914], [522, 897], [333, 756]], 3, 0], [None, 0, 0], [[[607, 907], [510, 894], [345, 779]], 3, 0], [None, 0, 0], [None, 0, 0]]
Java 提取代码
暂时只用颜色将标志位置显示出来,可根据需要修改代码。
- 新建一个空java script,将这个空java script命名为“test.java”, 将以下代码Copy paste
- 新建一个空txt 文档,将这个空文档命名为“test.txt"将上面“txt 格式的文件内容”中的内容Copy paste
import java.io.*;
import java.util.*;
public class test {
public static void main(String[] args) throws IOException {
addtest();
}
public static void addtest() throws IOException {
ArrayList data = new ArrayList();
File file = new File("test.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
StringBuffer sb = new StringBuffer();
String line = br.readLine();
fr.close();
process(line);
}
public static void process(String line){
char[] char_line = line.toCharArray();
int count_left = 0;
int count_right = 0;
int index = 0;
Queue tmp = new LinkedList();
for (char ch: char_line) {
if(ch=='['){
count_left++;
if(count_left-count_right>1){
tmp.add(ch);
}
if(count_left-count_right==2){
System.out.print("\033[31m l_"+count_left+'[');
}else{
System.out.print("\033[0m l_"+count_left+'[');
}
}else if(ch==']') {
count_right++;
tmp.add(ch);
if(count_left-count_right==1){
System.out.print("\033[32m"+" r_"+count_right+']'+'\n');
String tmp_str = "";
while(!tmp.isEmpty()){
System.out.print("\033[32m"+tmp.peek());
tmp_str+=tmp.poll();
}
index = 0;
System.out.println("");
process(tmp_str);
}else{
System.out.print("\033[35m r_"+count_right+']');
}
}else if(ch==','){
System.out.print("\033[34m ,_"+index);
if(count_left-count_right==2){
index++;
}
}else {
System.out.print("\033[0m "+ch);
tmp.add(ch);
}
}
}
}
例子输出
若有时间,会继续完善。。。希望路过的筒子,留下宝贵的意见/建议