java打开一个成语及其释义的文本文件,要求遍历每一行,分割成语与释义,计算每个成语末尾字在获得的成语列表中有多少成语开头与它接上,将结果在每一行后面添加,内容输出为新的文件
时间: 2024-03-08 13:46:53 浏览: 19
好的,您的问题和之前的问题是相同的,我已经回答了。以下是代码示例:
```java
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("idiom.txt"));
List<String> idiomList = new ArrayList<>();
Map<Character, List<String>> idiomMap = new HashMap<>();
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
String idiom = parts[0];
idiomList.add(idiom);
char lastChar = idiom.charAt(idiom.length() - 1);
if (!idiomMap.containsKey(lastChar)) {
idiomMap.put(lastChar, new ArrayList<>());
}
idiomMap.get(lastChar).add(idiom);
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("idiom_result.txt"));
for (String idiom : idiomList) {
char lastChar = idiom.charAt(idiom.length() - 1);
int count = idiomMap.containsKey(lastChar) ? idiomMap.get(lastChar).size() : 0;
bw.write(idiom + " " + count);
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们假设输入文件idiom.txt每一行的格式为“成语 释义”,并且成语和释义之间用空格分隔。输出文件idiom_result.txt每一行的格式为“成语 数量”,其中数量表示以该成语末尾字为开头的成语数量。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)