java统计短单词的个数

//by ysy 2018年3月6日

public class 统计短单词的数量 {
	  //--------------------统计短单词的个数----------------------------
	 @Test
	public void testName0() throws Exception {
		 long count = Files.lines(Paths.get("src/java8.txt"), Charset.defaultCharset()).parallel()
				// 字符串流--分割--字符串流
				.flatMap(str -> Arrays.stream(str.split("[^a-zA-Z]+")))
				// 去掉\n
				.filter(word -> word.length() >0)
				.filter(word -> word.length() < 12 )
				.count();
		System.out.println(count);
	}
	
	
	
		@Test
		public void testName_1() throws Exception {
			// Stream
			String conts = new String(Files.readAllBytes(Paths.get("src/java8.txt")));
			// 将字符串分割为单词
			List<String> asList = Arrays.asList(conts.split("[^a-zA-Z]+"));
			long count = asList.stream()
					           .parallel()
					           .filter(word -> word.length() >0)
					           .filter(s -> s.length() < 12)
					           .count();
			System.out.println("短单词个数" + count);

		}
	    //如何手工统计呢,版本1:不支持并发
	    @Test
		public void testName() throws Exception {
	    	int count[]=new int[12];
	    	String conts=new String(
		    		 Files.readAllBytes(Paths.get("src/java8.txt"))
		    		 );
	    	 List<String> asList = Arrays.asList(conts.split("[^a-zA-Z]+"));
	         System.out.println(asList);
	         asList.stream()
//	        	    .parallel()
	                            .forEach(s->{
	                            	if (s.length()<12 && s.length()>0) {
	                            		count[s.length()]++;
									}
	                            });
	         
	      int sum= IntStream.of(count)
	         .sum();
	     System.out.println("总个数:"+sum);
		}
	    
	    //改进,使用AtomicInteger,支持并发
	    @Test
	  	public void testName2() throws Exception {
	    	AtomicInteger count = new AtomicInteger(0);
	      	String conts=new String(
	  	    		 Files.readAllBytes(Paths.get("src/java8.txt"))
	  	    		 );
	      	 List<String> asList = Arrays.asList(conts.split("[^a-zA-Z]+"));
	           System.out.println(asList);
	           asList.stream()
	          	    .parallel()
		             .forEach(s->{
		              	if (s.length()<12 && s.length()>0) {
		              		count.incrementAndGet();
						}
		              });
	           
	       System.out.println("总个数:"+count.get());
	  	}
	      
}


Java 统计文本文件中单词个数可以通过以下步骤实现: 1. 使用 `BufferedReader` 类读取文本文件内容。 2. 将文本内容按照空格、换行符等分隔符进行分割,得到一个单词列表。 3. 遍历单词列表,统计单词的出现次数。 4. 输出单词个数。 下面是一个 Java 实现的例子: ```java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class WordCount { public static void main(String[] args) { String fileName = "text.txt"; Map<String, Integer> wordCount = new HashMap<>(); try (BufferedReader br = new BufferedReader(new FileReader(fileName))) { String line; while ((line = br.readLine()) != null) { String[] words = line.split("\\s+"); for (String word : words) { if (wordCount.containsKey(word)) { wordCount.put(word, wordCount.get(word) + 1); } else { wordCount.put(word, 1); } } } } catch (IOException e) { e.printStackTrace(); } int totalWords = 0; for (int count : wordCount.values()) { totalWords += count; } System.out.println("单词总数:" + totalWords); System.out.println("不同单词数:" + wordCount.size()); } } ``` 这个例子中,我们首先使用 `BufferedReader` 类读取指定的文本文件,并按行读取文件内容。然后,我们使用 `split` 方法对每一行文本内容进行分割,得到一个单词列表 `words`。接下来,我们遍历 `words` 列表,统计每个单词的出现次数,并将结果保存在一个 `HashMap` 对象 `wordCount` 中。最后,我们输出单词的总数和不同单词个数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值