gpt4 book ai didi

Java txt 解析器

转载 作者:行者123 更新时间:2023-11-30 06:31:36 24 4
gpt4 key购买 nike

我正在尝试编写一个java程序来打开一个包含文本段落的.txt文件。然后我想将特定的句子解析到文件中。具体来说“应该有声明。例如:

测试.txt

Hello all. Here is a a packing list. You should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet.

目标输出:

Should have a toothbrush. Should have a phone charger. Should have your wallet.

现在我的文件选择器工作正常。现在我只是想分解各个句子,然后我可以回去添加“应该有逻辑”。现在程序正在识别不同的句子,但只是不断重印完整的段落。任何帮助我解决这个问题的帮助将不胜感激。

import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;

public class PickAFile {
@SuppressWarnings("resource")
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();

int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {

try {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());

Scanner input = new Scanner(System.in);

File file = new File(chooser.getSelectedFile().getName());

input = new Scanner(file);

while (input.hasNextLine()) {
String message = input.nextLine();
String[] sentences = message.split("(?<=[.!?])\\s* ");
for (String s : sentences) {
System.out.println(message);
}
}

input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

输出:

You chose to open this file: test.txt Hello all. Here is a a packing list. You should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet.

Hello all. Here is a a packing list. You should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet.

Hello all. Here is a a packing list. You should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet.

Hello all. Here is a a packing list. You should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet.

Hello all. Here is a a packing list. You should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet.

最佳答案

        while (input.hasNextLine()) {
String message = input.nextLine();
String[] sentences = message.split("(?<=[.!?])\\s* ");
List<String> shouldHaves = new ArrayList<String>();
for (String s : sentences) {
if (s.contains("should have"))
shouldHaves.add(s);
}
for (String s : shouldHaves) {
System.out.println(s);
}
}

关于Java txt 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45984895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com