![](/img/trans.png)
[英]How to find a word is in which line of a text file and if the word exists in multiple line save the line number?
[英]How to find on which line a word is in Java
我正在嘗試創建一個程序來計算單詞在文本中出現的次數,並告訴您每行中出現多少次。 我設法找到了單詞出現的次數和文本中的行數,但是我找不到單詞出現在哪行以及出現了多少次。 請你幫助我好嗎? 到目前為止,這是我的代碼:
FileReader file = new FileReader("C:/Users/User/Desktop/test.txt");
BufferedReader buffer = new BufferedReader(file);
String line = buffer.readLine();
Map<String, Integer> hash = new HashMap<String, Integer>();
int counter = 0; //number of lines
while (line != null){
String[] words = line.split(" ");
for (String s : words) {
Integer i = hash.get(s);
hash.put(s, (i==null)? 1: i+1);
}
line = buffer.readLine();
counter = counter + 1;
}
System.out.println(hash);
System.out.println(counter);
它是每行的附加信息。 您只需要每行上的計數信息,因此簡單的Map是不夠的,您需要在每一行上使用Map的Map。
有兩種基本方法:
Map<Integer, Map<String, Integer>> hashOfHash = new HashMap<>();
List<Map<String, Integer>> list = new ArrayList<>();
第一行基於整數鍵值(即該行)創建Map的Map。
第二行正在創建地圖列表,因為列表中的順序已存儲,因此您只需迭代遍歷哪一行即可。
我建議第二行。
您還需要稍微修改一下while循環,以便能夠為每行創建新的地圖(考慮一下,您需要執行與第一行相同的操作)。
例如,這應該與您的程序相同,但是它將顯示每一行的結果:
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader file = new FileReader("C:/Users/User/Desktop/test.txt");
BufferedReader buffer = new BufferedReader(file);
String line = buffer.readLine();
List<Map<String, Integer>> list = new ArrayList<>();
while (line != null) {
Map<String, Integer> hash = new HashMap<String, Integer>();
String[] words = line.split(" ");
for (String s : words) {
Integer i = hash.get(s);
hash.put(s, (i == null) ? 1 : i + 1);
}
line = buffer.readLine();
list.add(hash);
}
int i=0;
for (Map<String, Integer> mapAtRow : list) {
i++;
System.out.println("at row " + i + "we found this: " + mapAtRow);
}
}
這是一個遞歸方法,使用String.indexOf可以計算單詞在一行中出現的次數。
您已經從bufferedReader中讀取了該行
String line = buffer.readLine();
然后在你的循環中
for (String s : words) {
int numberOfOccurencesOfS = countNumberOfTimesInALine(line,s);
}
countNumberOfTimesInALine
接收到原始行和您要計數的單詞作為參數。 要使用它,您還應該聲明一個這樣的類變量:private static int numberOfLineOccurences;
這是方法
public static int countNumberOfTimesInALine(String line, String word) {
if (line.indexOf(word) == -1) {
return numberOfLineOccurences;
} else {
numberOfLineOccurences++;
if (line.indexOf(word) + word.length() > line.length() -1 ) {
return numberOfLineOccurences;
}
return countNumberOfTimesInALine(
line.substring(line.indexOf(word) + word.length()), word );
}
}
這是一個用法示例:
String line = "DEMO TEST DEMO TEST DEMO TEST ALPHA BETA GAMMA";
System.out.println("Number of occurences of TEST is " + countNumberOfTimesInALine(line, "TEST"));
這是結果
TEST的發生次數是3
我已經在這里發布了與您類似問題的答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.