如何读取 txt 文件并根据 Java 中的数字和字符串分隔文本

How to read from a txt file and and seperate the text based on numbers and strings in Java

程序正在读取文本文件。文本文件的每一行都以 -2 到 2 之间的数字开头。数字是 then 后面跟着一个句子。 txt文件的前三行请看下面:

1 Campanella gets the tone just right -- funny in the middle of sad in the middle of hopeful .
-2 Nothing more than an amiable but unfocused bagatelle that plays like a loosely-connected string of acting-workshop exercises .
1 It 's a sharp movie about otherwise dull subjects .
1 ... it 's as comprehensible as any Dummies guide , something even non-techies can enjoy .
-1 -LRB- Green is -RRB- the comedy equivalent of Saddam Hussein , and I 'm just about ready to go to the U.N. and ask permission for a preemptive strike .

唯一应该阅读的行是那些有数字的行,一个 space 然后是按该顺序的文本。最后两行不应该考虑,因为它们在文本之前分别有 ...-。不过前三句还好。

我有一个名为 placeholder 的 class,其中包含以下字段:

public class placeholder implements Comparable<placeholder> {
    protected int score;
    protected String text;

    public placeholder(int score, String text) {
        this.score = score;
        this.text = text;
    }
}

我想要一个名为 readFile 的方法来逐行并将每一行存储到一个名为 reviewsDB 的列表中。列表中的每个对象都是 placeholder 类型,行首的数字是 score 值,后面的词是 text 值。我可以在以下区域中输入什么代码来分隔数字和文本之间的每一行?

    public static List<placeholder> readFile(String filename) {

        File movieReviews = new File("reviews.txt");

        try {

            Scanner scanner = new Scanner(movieReviews);
            scanner.nextLine();

            List<placeholder> reviewsDB = new ArrayList<placeholder>();

            while (scanner.hasNextLine()) {
                int sentenceScore = 0;
                String sentenceText = null;

                //code to separate the number and text in each line here
                placeholder newSentence = new placeholder(sentenceScore, sentenceText);

                reviewsDB.add(newSentence);
            }

            return reviewsDB;
        }

        catch (Exception e) {

            System.out.println("Something went wrong");

            return null;
        }

    }

您可以使用 Files.readAllLines(Path, Charset) 获取表示文件内容的字符串列表。然后您可以遍历列表并使用 String.split(Regex, Limit) 将字符串分成几部分。然后你可以从部件创建一个新的占位符对象。

参见:

您可以使用正则表达式。最好匹配模式。您可能有 n 个字符,也有正负字符。如果开头也有 +,则可以添加 (-|+)

希望你没有科学记数法。

while (scanner.hasNextLine()) {
    int sentenceScore = 0;
    String sentenceText = null;
    String line = scanner.nextLine();
    Matcher m = p.matcher(line);
    if (m.matches()) {
        System.out.println(m.group(1));
        System.out.println(m.group(2));
    }
    // code to separate the number and text in each line here
    placeholder newSentence = new placeholder(sentenceScore, sentenceText);

    reviewsDB.add(newSentence);
}

我使用了下面的正则表达式

Pattern p = Pattern.compile("^(-?\d+)(.*)");

- 是可选的 - -? 意味着这个 然后一位或多位数字 - \d+

那么第二组就是第一组之后的任意字符- (.*)

你可以玩你的输入here我在这里测试了你的输入。

  • 使用Files#lines
  • 将文件读入流
  • 使用正则表达式过滤符合条件的行 "-?\d\s\w+.*"
  • 使用 String#split 使用 space 作为分隔符将每行分成两部分,并将结果数组的长度限制为两个 line.split("\s",2)
  • 将流收集到 Placeholder 个对象的列表

示例代码:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example {

    public static void main(String[] args) {
        List<placeholder> list= readFile("path to your file");
        list.forEach(System.out::println);
    }
    public static List<placeholder> readFile(String filename) {
        List<Placeholder> reviewsDB = new ArrayList<>();
        try (Stream<String> content = Files.lines(Paths.get(filename))) {
            reviewsDB = content
                    .filter(line -> line.matches("-?\d\s\w+.*"))
                    .map(line -> line.split("\s",2))
                    .map(arr -> new placeholder(Integer.parseInt(arr[0]), arr[1]))
                    .collect(Collectors.toList());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return reviewsDB;
    }
}