Menu
CoddyTech

统计不重复单词数

本课属于 Coddy Dart 学习旅程的“逻辑与流程控制”单元。第 55 课,共 65 课。

challenge icon

挑战

简单

继续完成你的文本分析器项目,接下来你将实现唯一单词计数功能。这一步会使用 Set 自动从单词列表中删除重复项,从而统计文本中有多少个不同的单词。

  1. 使用你在前面的设置步骤中创建的 textToAnalyze 变量
  2. 使用你在字符计数步骤中创建的 totalCharacters 变量
  3. 使用你在拆分单词步骤中创建的 wordList 变量
  4. 使用你在单词计数步骤中创建的 totalWords 变量
  5. 使用 Set.from() 将单词列表转换为 Set,以自动删除重复的单词
  6. 将生成的 Set 存储在名为 uniqueWordsSet 的变量中
  7. 使用 Set 的 .length 属性统计唯一单词的数量
  8. 将唯一单词数量存储在名为 uniqueWordCount 的变量中
  9. 按照下方显示的准确格式展示唯一单词分析结果
  10. 正确格式化并显示原始文本、字符数、单词列表、单词总数、唯一单词集合和唯一单词数量

例如,如果你的文本分析器使用 "Hello world hello" 进行设置,程序应输出:

Text Analysis Tool - Unique Words
====================================
Analyzing text: "Hello world hello"
Total characters: 17
Words found: [Hello, world, hello]
Total words: 3
====================================
Unique Word Analysis Results:
Unique words: {Hello, world, hello}
Unique word count: 3
====================================
Unique word analysis completed successfully.

如果你的文本分析器使用 "The cat and the dog" 进行设置,程序应输出:

Text Analysis Tool - Unique Words
====================================
Analyzing text: "The cat and the dog"
Total characters: 19
Words found: [The, cat, and, the, dog]
Total words: 5
====================================
Unique Word Analysis Results:
Unique words: {The, cat, and, the, dog}
Unique word count: 5
====================================
Unique word analysis completed successfully.

如果你的文本分析器使用 "apple banana apple cherry banana" 进行设置,程序应输出:

Text Analysis Tool - Unique Words
====================================
Analyzing text: "apple banana apple cherry banana"
Total characters: 33
Words found: [apple, banana, apple, cherry, banana]
Total words: 5
====================================
Unique Word Analysis Results:
Unique words: {apple, banana, cherry}
Unique word count: 3
====================================
Unique word analysis completed successfully.

你的程序应使用 Set.from() 将单词列表转换为 Set。这个操作会自动删除重复的单词,同时保留唯一的单词。Set 的 .length 属性会给出唯一单词的数量。这项分析有助于了解文本词汇的丰富程度,并会在接下来的课程中与其他指标一起使用。

亲手试试

import 'dart:io';

void main() {
  String? textToAnalyze = stdin.readLineSync();
  int totalCharacters = textToAnalyze!.length;
  List<String> wordList = textToAnalyze.split(' ');
  int totalWords = wordList.length;
  
  print('Text Analysis Tool - Word Count');
  print('====================================');
  print('Analyzing text: "$textToAnalyze"');
  print('Total characters: $totalCharacters');
  print('Words found: $wordList');
  print('====================================');
  print('Word Count Results:');
  print('Total words: $totalWords');
  print('====================================');
  print('Word counting completed successfully.');
}

逻辑与流程控制中的所有课

自己练习: Dart 在线编译器