如何在java中搜索文本文件中的句子
嗨,我正在尝试做一个简单的搜索应用程序,它在文本文件中定义一个单词或多个句子(多个单词、两个单词或多个单词),然后返回这个单词或句子在文本文件中出现的次数 我的测试文本文件是:如何在java中搜索文本文件中的句子,java,regex,Java,Regex,嗨,我正在尝试做一个简单的搜索应用程序,它在文本文件中定义一个单词或多个句子(多个单词、两个单词或多个单词),然后返回这个单词或句子在文本文件中出现的次数 我的测试文本文件是: hi hi hi hello what is this from her what is this i'm new i'm new 我的搜索功能是: public int search(String text,String filePath) throws IOException { int coun
hi
hi
hi
hello
what is this from her what is this
i'm new
i'm new
我的搜索功能是:
public int search(String text,String filePath) throws IOException
{
int count = 0;
String line;
FileReader fr = new FileReader(filePath);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null)
{
if(line.toLowerCase().contains(text))
{
count++;
}
}
return count;
}
所以我的问题是在测试文本文件中,我可以从句子中找到句子(这是什么)(这是她写的什么是这)一次,在(这是她写的什么是这)句子中有两个句子(这是什么)
我在代码中理解这一点
if(line.toLowerCase().contains(text))
{
count++;
}
在第一次出现(what is this)语句时,它返回true并继续执行,并且从不检查同一行中是否再次出现相同的语句,并且只返回1而不是2,因此请帮助我尝试每件事尝试此代码以使其更快
public int search(String text, String filePath) throws IOException {
int count = 0;
String line;
text = text.toLowerCase();
FileReader fr = new FileReader(filePath);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
int fromIndex = 0;
int index = -1;
while ((index = line.toLowerCase().indexOf(text, fromIndex)) != -1) {
count++;
fromIndex = index + text.length();
}
}
fr.close();
br.close();
return count;
}
对于单线娱乐:
public int search(String text,String filePath) throws IOException
{
int count = 0;
String line;
FileReader fr = new FileReader(filePath);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine().toLowerCase()) != null)
{
for (; line.contains(text); line = line.replaceFirst(text, ""), count++);
}
return count;
}
@aelor,因为OP希望在Java中执行此操作。在读取行后,您必须使用另一个循环手动计算每行中搜索字符串的出现次数。你真正想问的是:我不理解大部分问题,但我猜你想用
StringUtils.countMatches
@NeplatnyUdaj替换String.contains
,这似乎是他想要的。他的问题是count的增量不会超过一次,因为它会在if找到第一个匹配项后继续到下一行。是的,正如@NeplatnyUdaj所说的,只需一个count+=StringUtils.countMatches()就可以了。使用regex时,文本将必须转义,并且仅用于字符串常量太耗时。它返回的计数=7BufferedWriter
和FileReader
未关闭。您必须关闭它。使用finally
子句关闭流,以完全确保它在任何情况下都必须关闭,即使遇到任何异常。