Java 提取 string 字符串格式的 Python list

目的

项目中,遇到需要读取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 提取代码

暂时只用颜色将标志位置显示出来,可根据需要修改代码。

  1. 新建一个空java script,将这个空java script命名为“test.java”, 将以下代码Copy paste
  2. 新建一个空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);
			}
		}
	}
}

例子输出

例子

若有时间,会继续完善。。。希望路过的筒子,留下宝贵的意见/建议

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值