【发布时间】:2015-07-17 11:50:54
【问题描述】:
我正在处理文本处理,我必须找到提到任何给定单词的推文数量。例如:
tweet 1: I had an egg for breakfast this morning
tweet 2: This is the book that I'll give to you tomorrow morning
tweet 3: I went there yesterday morning but you were not home. Did you go to her house this morning?
given word: this morning
对于上面的示例,频率应该为 2,因为只有两条推文(推文 1 和 3)以与给定单词完全相同的方式提及给定单词。 我担心如果我当前的实现效率低下(在某些方面),也许有更好的方法来做到这一点。到目前为止,我所做的是首先,我尝试获取所有包含给定单词的推文。
public int getDF(String term) throws FileNotFoundException, IOException{
int frequency = 0;
File[] paths = f.listFiles();
for(File f:paths){
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
String[] termTokens = term.split(" ");
while((line=br.readLine())!=null){
if(line.toLowerCase().contains(term)){
if(termTokens.length > 1){ //just for multi-word
if(getDFUtil(line.toLowerCase(), term.toLowerCase()))
frequency++;
}else
frequency++;
}
}
}
return frequency;
}
对于给定的多词,我调用函数 getDFUtil 来检查推文是否真的包含给定顺序的词。
public boolean getDFUtil(String tweet, String term){
String[] tweetTokens = tweet.split(" ");
String[] termTokens = term.split(" ");
int chosenIndex = 0;
int nextIndex = 0;
if(termTokens.length > 1){
for(int j=0;j<termTokens.length;j++){
for(int i=0;i<tweetTokens.length;i++){
if(termTokens[j].equals(tweetTokens[i]) && j==0){
chosenIndex = i;
nextIndex = i;
}else if(termTokens[j].equals(tweetTokens[i])){
nextIndex = i;
}
}
}
if(nextIndex - chosenIndex == termTokens.length - 1)
return true;
}else if(tweet.contains(term))
return true;
return false;
}
然而,就像我之前提到的,我想知道(而且应该是)是否有更好或更简单但功能强大的方法来做到这一点。
【问题讨论】:
标签: java string search twitter match