学以致用——Java源码——统计用户输入的一句话中重复的词(词频统计)(Counting Duplicate Words)

源码:

//Exercise 16.16: DuplicateWordCount.java
//16.16 (Counting Duplicate Words) Write a program that determines and prints the number of
//duplicate words in a sentence. Treat uppercase and lowercase letters the same. Ignore punctuation.
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;

public class DuplicateWordCount
{
public static void main(String[] args)
{
   // create HashMap to store String keys and Integer values
   Map<String, Integer> myMap = new HashMap<>(); 

   createMap(myMap); // create map based on user input
   displayMap(myMap); // display map content
} // end main

// create map from user input
private static void createMap(Map<String, Integer> map) 
{
   Scanner scanner = new Scanner(System.in); // create scanner
   System.out.println("Enter a string:"); // prompt for user input
   String input = scanner.nextLine();

   // tokenize the input
   String[] tokens = input.split(" ");
            
   // processing input text 
   for (String token : tokens) 
   {
      String word = token.toLowerCase(); // get lowercase word
               
      // if the map contains the word
      if (map.containsKey(word)) // is word in map
      {
         int count = map.get(word); // get current count
         map.put(word, count + 1); // increment count
      } 
      else 
         map.put(word, 1); // add new word with a count of 1 to map
   } 
   
   scanner.close();
} 

// display map content
private static void displayMap(Map<String, Integer> map) 
{     
   Set<String> keys = map.keySet(); // get keys
   int duplicateWords = 0;

   // sort keys
   TreeSet<String> sortedKeys = new TreeSet<>(keys);

   System.out.printf("%nMap contains:%nKey\t\tValue%n");

   // generate output for each key in map
   for (String key : sortedKeys)
   {  if (map.get(key)>1)
	   {  duplicateWords ++;
	      System.out.printf("%-10s%10s%n", key, map.get(key));
	   }
   }
   
   System.out.printf(
      "%nDuplicate Words: %d%n", duplicateWords);
} 
} // end class

运行结果:

Enter a string:
高 桌子 低 桌子 都是 桌子 他 大舅 他 二舅 都是 他舅

Map contains:
Key		Value
他                  2
桌子                 3
都是                 2

Duplicate Words: 3

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值