来自格式化文件的 Java 输入

发布于 2024-10-05 10:19:27 字数 371 浏览 0 评论 0原文

我正在尝试从具有各种不同行的文件中获取输入。

例如,格式为书名,作者:借阅人第二名名字:借阅人状态

这里有一些示例行。

The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10

因此,我在设置扫描仪后尝试使用 useDelimiter,但由于有些行较短,我不知道该怎么做。

I'm trying to getting input from a file which has various different lines.

e.g. the format is Book title, Author:Borrower second name First Name:Borrower state

here's some example lines.

The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10

Crime And Punishment, Fyodor Dostoyevsky

The Clan Of The Cave Bear, Jean M Auel

The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10

So I tried to use useDelimiter after setting up a scanner, but since some line are shorter I don't no quite what to do.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

风铃鹿 2024-10-12 10:19:27

这是一个基于正则表达式的解决方案:

import java.io.*;
import java.util.regex.*;

public class Test {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader("data.txt"));

        Pattern p = Pattern.compile("(.+?),(.+?)(?::(.+?):(\\d+ \\d+ \\d+))?");

        String line;
        while (null != (line = br.readLine())) {
            Matcher m = p.matcher(line);
            if (m.matches()) {
                String title = m.group(1);
                String author = m.group(2);
                String borrower = m.group(3);
                String data = m.group(4);

                System.out.println("Title:  " + title);
                System.out.println("Author: " + author);
                if (borrower != null) {
                    System.out.println("    Borrower: " + borrower);
                    System.out.println("    Data:     " + data);
                }
            }
            System.out.println();
        }

        br.close();
    }
}

给定您的示例输入,它会打印:

Title:  The Lord of the Rings
Author:  JRR Tolkien
    Borrower: McInnes Elizabeth
    Data:     13 11 10

Title:  Crime And Punishment
Author:  Fyodor Dostoyevsky

Title:  The Clan Of The Cave Bear
Author:  Jean M Auel

Title:  The God Of Small Things
Author:  Arundhati Roy
    Borrower: Robins Joshua
    Data:     20 11 10

Here is a solution based on regular expressions:

import java.io.*;
import java.util.regex.*;

public class Test {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new FileReader("data.txt"));

        Pattern p = Pattern.compile("(.+?),(.+?)(?::(.+?):(\\d+ \\d+ \\d+))?");

        String line;
        while (null != (line = br.readLine())) {
            Matcher m = p.matcher(line);
            if (m.matches()) {
                String title = m.group(1);
                String author = m.group(2);
                String borrower = m.group(3);
                String data = m.group(4);

                System.out.println("Title:  " + title);
                System.out.println("Author: " + author);
                if (borrower != null) {
                    System.out.println("    Borrower: " + borrower);
                    System.out.println("    Data:     " + data);
                }
            }
            System.out.println();
        }

        br.close();
    }
}

Given your sample input, it prints:

Title:  The Lord of the Rings
Author:  JRR Tolkien
    Borrower: McInnes Elizabeth
    Data:     13 11 10

Title:  Crime And Punishment
Author:  Fyodor Dostoyevsky

Title:  The Clan Of The Cave Bear
Author:  Jean M Auel

Title:  The God Of Small Things
Author:  Arundhati Roy
    Borrower: Robins Joshua
    Data:     20 11 10
百思不得你姐 2024-10-12 10:19:27

逐行读取文件,使用[^,:]正则表达式匹配每行中的数据(顺序find将带来标题、作者、借阅者、状态、如果有的话)。

Read the file line by line, use the [^,:] regular expression to match data in each line (sequential find will bring title, author, and borrower, state, if any).

阳光下的泡沫是彩色的 2024-10-12 10:19:27

你可以使用 .split()

try {
    FileInputStream fstream = new FileInputStream("input.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String line;
    String author;
    String title;
    String borrower;
    String date;

    while ((line = br.readLine()) != null)   {
      (author,title) = line.split(",");

      if (line.contains(":")
        (title,borrower,date) = title.split(":");

      /*** Do what you need to do with the values here ***/
    }

    in.close();

} catch (Exception e) {
    e.printStackTrace();
}

You could use .split()

try {
    FileInputStream fstream = new FileInputStream("input.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String line;
    String author;
    String title;
    String borrower;
    String date;

    while ((line = br.readLine()) != null)   {
      (author,title) = line.split(",");

      if (line.contains(":")
        (title,borrower,date) = title.split(":");

      /*** Do what you need to do with the values here ***/
    }

    in.close();

} catch (Exception e) {
    e.printStackTrace();
}
又爬满兰若 2024-10-12 10:19:27

为什么总是建议对于如此琐碎的任务使用正则表达式之类的超大工具?为什么不简单地使用旧的 line.indexOf()line.lastIndexOf() 方法呢?

Why always for such trivial tasks such oversized tools like regular expressions are suggested? Why not simply use the good old line.indexOf() or line.lastIndexOf() methods?

莫多说 2024-10-12 10:19:27

我将分割每一行(使用 String.split),并传入冒号作为分隔符。然后对 split 返回的第一个元素使用 lastIndexOf(',') ,以便将作者与书籍分开:

public class ReadCrappyInput {

    public static List<String> testData() {
        List<String> lines = new ArrayList<String>();
        lines.add("The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10");
        lines.add("Crime And Punishment, Fyodor Dostoyevsky");
        lines.add("The Clan Of The Cave Bear, Jean M Auel");
        lines.add("The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10");
        return lines;
    }

    public Map<String, String> readLine(String line) {
        String[] parts = line.split(":");
        int endOfTitleIndex = parts[0].lastIndexOf(',');
        Map<String, String> map = new HashMap<String, String>();
        map.put("title", parts[0].substring(0, endOfTitleIndex));
        map.put("author", parts[0].substring(endOfTitleIndex + 1).trim());    
        if (parts.length > 1) {
            map.put("borrower", parts[1]);
        }
        if (parts.length > 2) {
            map.put("data", parts[2]);
        }
        return map;
    }

    public static void main(String[] args) {
        ReadCrappyInput r = new ReadCrappyInput();
        for (String s : testData()) {
            System.out.println(r.readLine(s));
        }
    }
}

I would split each line (using String.split) passing in the colon as the delimiter. Then use lastIndexOf(',') on the first element returned by split in order to separate the author from the book:

public class ReadCrappyInput {

    public static List<String> testData() {
        List<String> lines = new ArrayList<String>();
        lines.add("The Lord of the Rings, JRR Tolkien:McInnes Elizabeth:13 11 10");
        lines.add("Crime And Punishment, Fyodor Dostoyevsky");
        lines.add("The Clan Of The Cave Bear, Jean M Auel");
        lines.add("The God Of Small Things, Arundhati Roy:Robins Joshua:20 11 10");
        return lines;
    }

    public Map<String, String> readLine(String line) {
        String[] parts = line.split(":");
        int endOfTitleIndex = parts[0].lastIndexOf(',');
        Map<String, String> map = new HashMap<String, String>();
        map.put("title", parts[0].substring(0, endOfTitleIndex));
        map.put("author", parts[0].substring(endOfTitleIndex + 1).trim());    
        if (parts.length > 1) {
            map.put("borrower", parts[1]);
        }
        if (parts.length > 2) {
            map.put("data", parts[2]);
        }
        return map;
    }

    public static void main(String[] args) {
        ReadCrappyInput r = new ReadCrappyInput();
        for (String s : testData()) {
            System.out.println(r.readLine(s));
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文