java - 如何在java中按初始字符计算平均词条长度?
问题描述
我有一个文件(txt),其中包含一段文本,我必须通过 java 中的初始字符计算平均术语长度。例如,如果有 4 个单词“purple, brown, pink, black”,输出应该是;p = 5 b = 5
我想了好几个小时,但我做不到我能做的只是拆分单词。我不知道如何制作具有相同初始字符的单词列表。
try(Scanner scanner = new Scanner(new FileReader("sampleText.txt"))) {
ArrayList<String> arrlist = new ArrayList<String>();
while (scanner.hasNext()) {
String sampleText = scanner.nextLine();
String[] array = sampleText.split(" ");
for (int i = 0; i < array.length; i++) {
if (array[i].charAt(0) = Integer ) //tried to not take numbers didn't work
System.out.println(array[i]);
arrlist.add(array[i]);
}
System.out.print(array);
break;
}
}
catch (FileNotFoundException e) {
System.out.println("FNF Exception");
}
catch (ArrayIndexOutOfBoundsException a) {
System.out.println("AIOoB Exception");
}
}
解决方案
您可以通过以下方式解决它:
- 用逗号分割字符串,后跟空格(即
,\\s+
),将生成的字符串存储到 aList<String>
中,然后对列表进行排序。 - 使用 a
Map<Character, Double>
存储计算的数据,其中键是初始字符,值是平均术语长度。 - 使用变量来计算总和并对元素进行计数,以便计算平均值。使用内部循环,浏览列表,直到获得具有不同首字母的元素。
- 一旦你得到一个具有不同首字母的元素,就终止内部循环。此时,将带有平均值的首字母存储到地图中。
演示:
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
String str = "purple, brown, pink, black";
// Split the string and store into a List<String>
List<String> list = Arrays.asList(str.split(",\\s+"));
// Sort the list
list.sort(Comparator.naturalOrder());
// Use a Map<String, Integer> to store the data
Map<Character, Double> map = new LinkedHashMap<>();
for (int i = 0; i < list.size(); i++) {
// Get the element and move to the loop counter to the next index
String element = list.get(i++);
double sum = element.length();
Character ch = Character.valueOf(element.charAt(0));
int count = 1;
// Starting with the next index, iterate the list until you find an element with
// a different initial letter
while (i < list.size() && ch.equals(Character.valueOf(list.get(i).charAt(0)))) {
// Add the length of element and move the outer loop counter to the next index
sum += list.get(i++).length();
count++;
}
map.put(ch, sum / count);
// Adjust the the outer loop counter by decrementing by 1
i--;
}
// Display the result
System.out.println(map);
}
}
输出:
{b=5.0, p=5.0}
推荐阅读
- azure-devops - 如何查找在 azure devops 中配置的代理池中使用的 Windows Server 和 Visual Studio 版本
- sql-server - 关闭 VS 中由 SSRS 报表向导创建的报表的默认列下划线
- python - 使用 BeautifulSoup 在 Python 中进行网页抓取
- java - 在 Spring Boot 中动态设置 hibernate.dialect 属性
- python - 访问 dask 集群中分散数据的成本
- html - 2 列列表由其标题分隔
- javascript - 有没有办法在一个函数定义中提供两组剩余参数?
- python - 在运算符及其文本表示之间进行转换
- reactjs - TypeError:- 类扩展值未定义不是构造函数或 null
- cassandra - Cassandra - HDD 与 SSD 的使用对吞吐量没有影响