将文本文件读入三维数组

3

我希望能够将文本文件中的内容读取到一个多维数组中。我的文本文件包含特定格式的字符串。

我只想将其存储到一个多维数组中。我尝试使用Java代码将其存储到字符串或字符串数组中,但我不知道如何将这种格式存储到多维数组中。有人可以帮助我吗?

我的文本文件read.txt包含以下内容:

    { { "Kim","is" "playing" },         { "NOUN", "VERB", "DET" } },
    { { "Shine","is" "eating"},         { "NOUN","DET" "VERB" } },
    { { "Kevin","lives","in","Holland"},  { "NOUN", "VERB ","DET","Holland"} }

我尝试的是:

什么我尝试的是:

    public class MyClass
    {
      static final String[][][] MULTI_ARRAY = new String[][][];
      public static void main(String args[]
      {
        for (String[][] myarray : MULTI_ARRAY) 

            String[] sentences = myarray[0];
            String[] partsofspeech = myarray[1];  
        }
      }}

      BufferedReader br=new BufferedReader(new FileReader("read.txt"));
      while(br.ready)
      {
         MULTI_ARRAY[][][]=br.readLine();

      }
   }

我希望我的3D数组以以下格式呈现:
    static final String[][][] MULTI_ARRAY = new String[][][] {
   { { "Kim","is" "playing" },         { "NOUN", "VERB", "DET" } },
    { { "Shine","is" "eating"},         { "NOUN","DET" "VERB" } },
    { { "Kevin","lives","in","Holland"},  { "NOUN", "VERB ","DET","Holland"} }
  };

你编译了这段代码吗? - Thusitha Thilina Dayaratne
@Mena,我认为这不是一个好选择,因为如果我考虑JSON格式,那么它应该是{"title":"jhdjashlashflfhlkdf"}的格式,但我的数据不应被视为JSON格式。 - chopss
我想将这个数组以与文本文件中相同的格式放置。 - chopss
您想设置一个格式,以便在Java中轻松解析,还是想解析您给定的确切格式? - maslan
一个真正疯狂的想法是将.java源代码放入静态字段中,然后编译它并使用ClassLoader进行加载。但是这需要用户安装JDK,并且这非常不安全。 - kajacx
显示剩余2条评论
3个回答

2

假设格式是每行一个2D块。我使用 ArrayList 而不是数组,因为您无法预先知道所需的大小。这是我的代码:

Scanner scan = new Scanner(new File("file.txt"));

List<List<List<String>>> d3 = new ArrayList<>();

while (scan.hasNextLine()) {
    String line = scan.nextLine();

    String[] splitted = line.split("(?<!\\\\)\\\"");
    List<List<String>> d2 = new ArrayList<>();
    d3.add(d2);

    List<String> d1 = new ArrayList<>();
    d2.add(d1);

    // ignore first and last
    for (int i = 1; i < splitted.length - 1; i++) {
        if ((i & 1) != 0) { // odd, add to list
            // unescape double quote and backslash
            d1.add(splitted[i].replace("\\\"", "\"").replace("\\\\", "\\"));
        } else { // even test if new array starts
            if (splitted[i].matches(".*\\{.*")) {
                d1 = new ArrayList<>();
                d2.add(d1);
            }
        }
    }
}

scan.close();
System.out.println(d3);

这个想法基于使用"来分割字符串,但是如果你在字符串中使用转义字符(\")的话,由于使用了negative lookbefore,仍然可以正确地进行分割。但是,如果字符串末尾有反斜杠,它将失败

编辑:

要将List<List<List<String>>>转换为String[][][],您可以使用此代码:

String[][][] result = new String[d3.size()][][];
for (int i = 0; i < result.length; i++) {
    result[i] = new String[d3.get(i).size()][];
    for (int j = 0; j < result[i].length; j++) {
        result[i][j] = new String[d3.get(i).get(j).size()];
        for (int k = 0; k < result[i][j].length; k++) {
            result[i][j][k] = d3.get(i).get(j).get(k);
        }
    }
}

System.out.println(Arrays.deepToString(result)); //see if result is ok

kajacx,谢谢您的回复,但我想要它以三维数组格式。我该如何转换? - chopss
System.out.println(Arrays.deepToString(result));和System.out.println(d3);输出的结果相同List<List<List<String>>>。 - chopss
如果你所说的“相同输出”是指相同的数据,那么是的,这就是整个想法。 - kajacx

1

请参见此答案:在Python Web应用程序中呈现换行符的方法

我认为它类似于状态机

[Start]
 |                                       
 v                                       
[Base-State]--{--->[2D-State]---{---->[1D-State]
|         ^         |     ^               |
|         |-----}----     |  read everything until next } into buffer,
EOF                       |  split by ',' into list, 
|                         |  append to multidimensional array
V                         |               |
[End]                     |----------------

以下是如何使用伪代码构建简单状态机的步骤:
state = "Base-State"
buff = ""
parser: while(true) {
   currChar = readchar()
   switch case(state) {
      case "Base-State":
         if (currChar == '{') {
            state = "2D-State"
         }
         else if (currChar == null) {
            break parser
         }
         break
      case "2D-State":
         if (currChar == '{') {
            state = "1D-State"
         }
         else if (currChar == '}') {
            state = "Base-State"
         }
         else if (currChar == null) {
            //throw error
         }
         break
      case "1D-State":
         if (currChar == '{') {
            //throw error
         }
         else if (currChar == null) {
            //throw error
         }
         else if (currChar == '}') {
            //split buffer into list, put into array at fitting place
            state = "2D-State"
         }
         else {
            buffer += currChar
         }
         break
   }
}

所以-每个状态对应于switch语句中的一个case,每个转换都由一个带有状态赋值的if语句组成,转换中的每个字符表示if语句中的条件。

Michael,我认为实现这个非常困难。 - chopss
请描述一下您遇到的困难。将其用语言表达出来会更好地帮助您理解,也许我可以帮您解决问题。 - Michel Müller

0
你应该尝试解析你的文本文件。 我找到了这个解析教程,但你也可以解析你的文本文件。

解析教程

你尝试的方法不是有效的。你必须理解你的代码将被编译。但文本文件部分是在编译后加载的,而缓冲读取器读取的文本不会被编译,编译后的程序无法读取它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接