统计不同长度单词数量

该博客介绍了一个Java程序,用于统计用户输入文本中每个单词的出现频率。目前程序能处理用户输入的字符串,目标是修改为读取文本文件的每一行。博主提供了程序代码,并提出可以使用SPL脚本来简化这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题】

I've created a Java program in Eclipse. The program counts the frequency of each word. For example if the user entered'I went to the shop'the program would produce the output'1 1 1 2'that is 1 word of length 1 ('I') 1 word of length 2 ('to') 1 word of length 3 ('the') and 2 words of length 4 ('went','shop').

I've created this program to read a string entered by the user but I'm wanting to adjust the code to read each line of a text file. Any help would be great.

import java.util.Scanner;

public class WordLengthFrequency

{

    public static void main(String[] args)

    {

        Scanner scan = new Scanner(System.in);

        while (true)

        {

            System.out.println("Enter text:");

            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;

            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++){   

                StringBuilder sb = new StringBuilder(i).append(i + "letter words:");

                for (int j = 1; j <= counts[i]; j++) {

                    sb.append('*');

                    System.out.println(i + "letter words:" + counts[i]);

                    System.out.println(sb);

                    System.out.println(("mean lenght:") + ((double) total / strings.length));

                }

            }

       }

    }

}

【回答】

       JAVA直接写很麻烦,用SPL写一个简单的脚本,然后集成进Java就行了,如何集成可以参考Java 如何调用 SPL 脚本

A
1=file("d:\\data.txt").read()
2=A1.words()
3=A2.groups(len(~):length;count(~):count)

A1:从文本读取字符串

A2:将字符串拆分成单个单词组成的序列

A3:对序列A2按照单词长度分组,并计算每组单词数量

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值