如何从Java中的txt文件中仅提取单词 [英] How to extract ONLY words from a txt file in Java
问题描述
所以我必须从文本文件中提取数据.
So I have to extract data from a text file.
这样设置文本文件.
3400 Moderate
310 Light
etc.
我需要提取数字,将它们存储在一个数组中,然后将字符串存储在另一个数组中,以便我可以根据数组中写入的内容对数字进行计算,然后将其输出到文件中.我已经讲完了最后一部分,当我从txt中提取数据时,我只是想不出如何从字符串中分离整数.文件.
I need to extract the numbers, store them in one array, and the strings, and store them in another array so I can do calculations to the numbers based on whats written in the array, and then output that to a file. I've got the last part down, I just cant figure out how to separate the ints from the strings when I extract the data from the txt. file.
这是我现在拥有的,但是它只是将int和单词提取为 String
.
Here is what I have now, but it's just extracting the int and the word as a String
.
import java.io.*;
import java.util.*;
public class HorseFeed {
public static void main(String[] args){
Scanner sc = null;
try {
sc = new Scanner(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
for(int i = 0; i< 100; i++){
System.out.print(arr[i]);
}
}
}
推荐答案
plz,请遵循代码.
plz, follow the code.
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HorseFeed {
public static void main(String[] args) throws FileNotFoundException, IOException {
List<String> lineList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Patric\\Desktop\\HorseWork.txt")));
String line;
while ((line = br.readLine()) != null) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(line);
if( pattern.matcher(line).matches()){
while(matcher.find()){
lineList.add(matcher.group());
}
}
}
}
}
其中lineList包含您的整数.
here lineList contains your integer.
这篇关于如何从Java中的txt文件中仅提取单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!