ChatGPT4 を使用して、ファイル内のさまざまな単語の数を読み取りやすくします。
ChatGPT4 認識を使用します。Java を使用して、ファイル内のさまざまな単語の数を読み取ります。
解析: このプログラムは、「file.txt」というファイルを読み取り、ファイル内の各単語の出現数をカウントします。文字列操作を使用して単語をクリーンアップし、HashMap を使用して各単語の出現数を保存します。最後に、プログラムは個別の単語の合計数を出力します。
//ChatGPT4完成的代码和我所需要的有点差异
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
public class CountDistinctWords {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
Map<String, Integer> wordCount = new HashMap<String, Integer>();
while (line != null) {
String[] words = line.split(" ");
for (String word : words) {
String cleanedWord = word.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
if (!cleanedWord.isEmpty()) {
if (wordCount.containsKey(cleanedWord)) {
int count = wordCount.get(cleanedWord);
wordCount.put(cleanedWord, count + 1);
} else {
wordCount.put(cleanedWord, 1);
}
}
}
line = reader.readLine();
}
reader.close();
System.out.println("Distinct words: " + wordCount.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
ChatGPT4 の使用は、ファイル内の中国語を除く文字とスペースで区切られた数字を読み取ることです。
読み込むファイルの中国語の数が思っていたのとは少し違いますが、大まかな方法は同じです。
主なプロセス: バッファ ストリームを使用してファイルを読み取り、ハッシュマップを使用して各行の中国語を読み取り、正規表現で中国語をフィルタリングし、各中国語をキーとして使用し、最後にハッシュマップのサイズを読み取るだけで済みます。中国人が何人いるのか知りたい。
//根据需求修改后的代码
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class readWordCount {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("read_word_count/file.txt"));
String line = null;
Map<Character, Integer> wordCount = null;
int count = 0;
wordCount = new HashMap<Character, Integer>();
while (true) {
line = reader.readLine();
if(line == null){
break;
}
line = line.replaceAll("[^\\u4E00-\\u9FA5]", "");
char[] words = line.toString().toCharArray();
for (char word : words) {
if (wordCount.containsKey(word)) {
count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1);
}
}
}
System.out.println("不同中文的个数: " + wordCount.size());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
テスト例:
abcd dsvsdvsdvsdvdsvd 王王 王
魯迅「百草園から三味書店まで」滴迪
結果:
異なる漢字の数: 13
记录每一个学习瞬间