【发布时间】:2020-05-05 04:03:30
【问题描述】:
在一个项目中,我试图查询特定用户句柄的推文,并在用户的推文中找到最常用的词,并返回该最常用词的频率。
下面是我的代码:
public String mostPopularWord()
{
this.removeCommonEnglishWords();
this.sortAndRemoveEmpties();
Map<String, Integer> termsCount = new HashMap<>();
for(String term : terms)
{
Integer c = termsCount.get(term);
if(c==null)
c = new Integer(0);
c++;
termsCount.put(term, c);
}
Map.Entry<String,Integer> mostRepeated = null;
for(Map.Entry<String, Integer> curr: termsCount.entrySet())
{
if(mostRepeated == null || mostRepeated.getValue()<curr.getValue())
mostRepeated = curr;
}
//frequencyMax = termsCount.get(mostRepeated.getKey());
try
{
frequencyMax = termsCount.get(mostRepeated.getKey());
return mostRepeated.getKey();
}
catch (NullPointerException e)
{
System.out.println("Cannot find most popular word from the tweets.");
}
return "";
}
我也认为显示我在上面的方法中调用的前两个方法的代码会有所帮助,如下所示。它们都在同一个类中,定义如下:
private Twitter twitter;
private PrintStream consolePrint;
private List<Status> statuses;
private List<String> terms;
private String popularWord;
private int frequencyMax;
@SuppressWarnings("unchecked")
public void sortAndRemoveEmpties()
{
Collections.sort(terms);
terms.removeAll(Arrays.asList("", null));
}
private void removeCommonEnglishWords()
{
Scanner sc = null;
try
{
sc = new Scanner(new File("commonWords.txt"));
}
catch(Exception e)
{
System.out.println("The file is not found");
}
List<String> commonWords = new ArrayList<String>();
int count = 0;
while(sc.hasNextLine())
{
count++;
commonWords.add(sc.nextLine());
}
Iterator<String> termIt = terms.iterator();
while(termIt.hasNext())
{
String term = termIt.next();
for(String word : commonWords)
if(term.equalsIgnoreCase(word))
termIt.remove();
}
}
对于相当长的代码 sn-ps,我深表歉意。但令人沮丧的是,即使我的 removeCommonEnglish() 方法显然是正确的(在另一篇文章中讨论),当我运行 mostPopularWord() 时,它返回“the”,这显然是我常用的英语单词列表的一部分已经并打算从列表中删除。我可能做错了什么?
更新 1: 这是 commonWords 文件的链接: https://drive.google.com/file/d/1VKNI-b883uQhfKLVg-L8QHgPTLNb22uS/view?usp=sharing
更新 2:我在调试时注意到的一件事是 而(sc.hasNext()) 在 removeCommonEnglishWords() 中被完全跳过。不过,我不明白为什么。
【问题讨论】:
-
显然对吗?首先确定这一点。在调用该方法后检查列表的内容,并查看它是否包含“the”。您的调试器以及 System.out.println() 都是您的朋友。
-
您也可以发
commonWords.txt,以便我们试用代码吗? -
@SreeKumar 它现在已经作为更新发布在上面。
标签: java string list hash iterator