有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

twitter使用java从推文中排除一些单词

我正试图编写一个程序,从特定用户那里检索推文,并统计最常用的单词。在我的代码中,除了重复次数之外,我还得到了用户时间线中写的每个单词。但我只需要得到最常用的单词和计数

我该如何修复代码才能做到这一点

for(Status status2 : status){
    status2.getText();
    //System.out.println(status2.getCreatedAt());

    String s = status2.toString();
    String[] splitted = s.split(" ");
    HashMap hm = new HashMap();
    int x;  

    for (int i = 0; i < splitted.length; i++) {
        if (!hm.containsKey(splitted[i])) {
            hm.put(splitted[i], 1);
        } else {
            hm.put(splitted[i], (Integer) hm.get(splitted[i]) + 1);
        }
        for (Object word : hm.keySet()){
            System.out.println(word + " " + (Integer) hm.get(word));
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    我使用了listString变量,但同样的概念也适用于推文。只需在每条推文上循环,获取消息所在的String,而不是在List对象中的String变量上循环

    • 在推文循环之外初始化map。当你在loop中初始化它时,它会为每条推文重新创建地图。这将删除您找到的任何数据
    • map在推文循环之外输出值。否则,您将在每次推文迭代中输出数据。这可能是你想要的结果,但从我收集的信息来看,这并不是你想要的
    • 生活质量类型更新,但您应该使用foreach循环来循环分割数组。不需要为int计数器使用额外的内存

    结果的问题是,您在每次迭代中都在重新创建地图,删除了所有以前的数据。如果在循环之前初始化映射,并且不重新初始化每个迭代,则可以在所有推文中跟踪数据。例如:

    public static void main(String[] args) throws Exception {
    
        List<String> statusTweets = new ArrayList<String>();
        statusTweets.add("At the bar");
        statusTweets.add("At the house");
        statusTweets.add("Out with friends");
    
        Map<String,Integer> wordHits = new HashMap<String,Integer>();
    
        for(String status : statusTweets){
            String[] statusSplitOnSpace = status.split(" ");
            for(String wordInStatus : statusSplitOnSpace){
                if (!wordHits.containsKey(wordInStatus)) {
                    wordHits.put(wordInStatus, 1);
                } else {
                    wordHits.put(wordInStatus, wordHits.get(wordInStatus)+1);
                }
            }
        }
    
        for(Entry<String,Integer> wordHit : wordHits.entrySet()){
            System.out.println("Word (" + wordHit.getKey() + ") was found " + wordHit.getValue() + " times.");
        }
    
    }
    

    循环完成后,您可以使用找到的数据执行所需的操作。找到较高的字数,删除某些单词,等等。我只是做了一个循环来输出结果。这让我:

    Word (the) was found 2 times.
    Word (with) was found 1 times.
    Word (bar) was found 1 times.
    Word (At) was found 2 times.
    Word (house) was found 1 times.
    Word (friends) was found 1 times.
    Word (Out) was found 1 times.