[英]searching in text file specific words using java
我有一个巨大的文本文件,我想搜索特定的单词并打印三个或三个以上的单词,到目前为止,我已经完成了此操作
public static void main(String[] args) {
String fileName = "C:\\Users\\Mishari\\Desktop\\Mesh.txt";
String line = null;
try {
FileReader fileReader =
new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
} catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}
仅用于打印文件,您可以告诉我什么是最好的处理方法。
您可以使用此方法在行中查找单词索引。
int index = line.indexOf(word);
如果存在,则从该索引开始到该行的末尾获取该行的子字符串。
String nextWords = line.substring(index);
现在使用String[] temp = nextWords.split(" ")
获取该子字符串中的所有单词。
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if (line.contains("YOUR_SPECIFIC_WORDS")) { //do what you need here }
}
听起来,您似乎正在寻找一种针对从文件中读取的每个文件行的基本“查找并替换所有”机制。 换句话说,如果当前读取的文件行恰好包含单词或短语,则您想在之后添加单词 ,然后用完全相同的单词加上您要添加的其他单词替换找到的单词。 从某种意义上说应该是这样的:
String line = "This is a file line.";
String find = "file"; // word to find in line
String replaceWith = "file (plus this stuff)"; // the phrase to change the found word to.
line = line.replace(find, replaceWith); // Replace any found words
System.out.println(line);
控制台输出为:
这是一个文件(加上这个东西)行。
不过,这里的主要要点是,您只想处理实际单词,而不要处理另一个单词内的相同短语,例如单词“ and”和单词“ sand” 。 您可以清楚地看到组成单词“ and”的字符也位于单词“ sand”中 ,因此上述示例代码也会对其进行更改。 String.contains()方法也以这种方式定位字符串。 在大多数情况下,如果您只想专门处理整个单词,那么这是不希望的,因此一个简单的解决方案是将正则表达式 (RegEx)与String.replaceAll()方法一起使用。 使用您自己的代码,它将看起来像这样:
String fileName = "C:\\Users\\Mishari\\Desktop\\Mesh.txt";
String findPhrase = "and"; //Word or phrase to find and replace
String replaceWith = findPhrase + " (adding this)"; // The text used for the replacement.
boolean ignoreLetterCase = false; // Change to true to ignore letter case
String line = "";
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
if (ignoreLetterCase) {
line = line.toLowerCase();
findPhrase = findPhrase.toLowerCase();
}
if (line.contains(findPhrase)) {
line = line.replaceAll("\\b(" + findPhrase + ")\\b", replaceWith);
}
System.out.println(line);
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file: '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file: '" + fileName + "'");
}
您当然会注意到在String.replaceAll()方法中使用的正则表达式中的转义\\ b单词边界元字符,特别是在该行中:
line = line.replaceAll("\\b(" + findPhrase + ")\\b", replaceWith);
这使我们只能处理整个单词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.