gpt4 book ai didi

java 对从文本文件中读取的字符串进行标记化

转载 作者:行者123 更新时间:2023-12-02 05:52:31 27 4
gpt4 key购买 nike

我有一个可以从我的计算机读取文本文件的程序。文本文件是标题列表。我试图弄清楚如何对返回的内容进行标记,以便我获得全名而不是片段。我能找到的所有示例都涉及常规数组,而我使用的是数组列表。我需要能够将每个字符串读回到数组列表中,并在 & 所在的位置将其截断。

文本文件如下所示:

星球大战&DVD&

指环王&DVD&

生化危机&DVD&

public static void main(String[] args) {

File f = new File("file.txt");
try {
ArrayList<String> lines = get_arraylist_from_file(f);
for (int x = 0; x < lines.size(); x++) {
System.out.println(lines.get(x));
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("done");

}

public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}

最佳答案

     public static ArrayList<String> get_arraylist_from_file(File f) throws FileNotFoundException {
Scanner scanner;
ArrayList<String> list = new ArrayList<String>();
scanner = new Scanner(f);
String s = scanner.nextLine();

while(scanner.hasNextLine()){
String[] tempList = s.split("&"); //This will give you this [title][ DVD]
String title = tempList[0];
String type = tempList[1].subString(1); //If you want the input at the place of DVD, with the space removed
list.add(title);
s = scanner.nextLine();
}
scanner.close();
return list;
}

关于java 对从文本文件中读取的字符串进行标记化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415688/

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