java编写:给定一个英文文本文件,进行切词并统计其中单词个数,存入一个文件中。
2个回答
展开全部
package Main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
int count = 0;
File file = new File("D:\\1.txt");
String s = "";
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
while ((s = br.readLine()) != null) {
buffer.append(s + '\n');
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("\\b[a-zA-Z]+\\b");
Matcher m = p.matcher(buffer.toString());
while(m.find()) {
System.out.println(m.group());
count ++ ;
}
System.out.println("总共:" + count + "个单词");
}
}
看看是不是你要的效果
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
int count = 0;
File file = new File("D:\\1.txt");
String s = "";
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
while ((s = br.readLine()) != null) {
buffer.append(s + '\n');
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("\\b[a-zA-Z]+\\b");
Matcher m = p.matcher(buffer.toString());
while(m.find()) {
System.out.println(m.group());
count ++ ;
}
System.out.println("总共:" + count + "个单词");
}
}
看看是不是你要的效果
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |