gpt4 book ai didi

Java - 词频

转载 作者:行者123 更新时间:2023-11-29 07:39:59 29 4
gpt4 key购买 nike

我在 Eclipse 中创建了一个 Java 程序。该程序计算每个单词的频率。例如,如果用户输入“I went to the shop”,程序将产生输出“1 1 1 2”,即 1 个字长 1 ('I') 1 个字长 2 ('to') 1 个字长度为 3('the')和 2 个长度为 4 的词('went','shop')。

这些是我得到的结果。我不希望显示带有 0 的输出。我怎样才能隐藏这些并且只显示 1,2,3,4,5 的结果。

The cat sat on the mat
words[1]=0
words[2]=1
words[3]=5
words[4]=0
words[5]=0


import java.util.Scanner;
import java.io.*;

public class mallinson_Liam_8
{

public static void main(String[] args) throws Exception
{

Scanner scan = new Scanner(new File("body.txt"));

while(scan.hasNext())
{

String s;
s = scan.nextLine();
String input = s;
String strippedInput = input.replaceAll("\\W", " ");

System.out.println("" + strippedInput);

String[] strings = strippedInput.split(" ");
int[] counts = new int[6];
int total = 0;
String text = null;

for (String str : strings)
if (str.length() < counts.length)
counts[str.length()] += 1;
for (String s1 : strings)
total += s1.length();

for (int i = 1; i < counts.length; i++){
System.out.println("words["+ i + "]="+counts[i]);
StringBuilder sb = new StringBuilder(i).append(i + " letter words: ");
for (int j = 1; j <= counts[i]; j++) {




}}}}}

最佳答案

我知道您要求使用 Java,但为了比较,下面是我在 Scala 中的做法:

val s = "I went to the shop"
val sizes = s.split("\\W+").groupBy(_.length).mapValues(_.size)
// sizes = Map(2 -> 1, 4 -> 2, 1 -> 1, 3 -> 1)

val sortedSizes = sizes.toSeq.sorted.map(_._2)
// sortedSizes = ArrayBuffer(1, 1, 1, 2)

println(sortedSizes.mkString(" "))
// outputs: 1 1 1 2

关于Java - 词频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320835/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com