字数不重复

时间:2012-08-02 00:51:10

标签: java count word

这是我使用java的单词计数程序。我需要重新编程这样的东西,某些东西;什么?什么!有些东西算作一个字。这意味着它不应该计算两次相同的单词,无论案例和标点符号。

import java.util.Scanner;
public class WordCount1
{
    public static void main(String[]args)
    {
        final int Lines=6;
        Scanner in=new Scanner (System.in);
        String paragraph = "";
        System.out.println( "Please input "+ Lines + " lines of text.");
        for (int i=0; i < Lines; i+=1)
        {
            paragraph=paragraph+" "+in.nextLine();
        }
        System.out.println(paragraph);
        String word="";
        int WordCount=0;
        for (int i=0; i<paragraph.length()-1; i+=1)
        {
            if (paragraph.charAt(i) != ' ' || paragraph.charAt(i) !=',' || paragraph.charAt(i)    !=';' || paragraph.charAt(i) !=':' )
            {
                word= word + paragraph.charAt(i);
                if(paragraph.charAt(i+1)==' ' || paragraph.charAt(i) ==','|| paragraph.charAt(i) ==';' || paragraph.charAt(i) ==':')
                {
                    WordCount +=1;
                    word="";
                }
            }
        }
        System.out.println("There are "+WordCount +" words ");
    }
}

8 个答案:

答案 0 :(得分:3)

由于这是作业,这里有一些提示和建议。

  • 有一个名为String.split的聪明的小方法,它使用指定为正则表达式的分隔符将字符串拆分为多个部分。如果以正确的方式使用它,这将为您提供“字数统计”问题的单行解决方案。 (如果你被告知不要使用split,你可以忽略它......虽然这是经验丰富的Java开发人员首先考虑的简单解决方案。)

  • 在向其他人展示代码之前,正确格式化/缩进代码。如果你的导师没有为此扣除标记,他/她就没有正常工作。

  • 使用标准Java命名约定。 Lines的大小写不正确。对于变量,它可以是LINES,对于变量可以是lines,但是以大写字母开头的混合大小写名称​​总是是类名。

    < / LI>
  • 在运算符(包括赋值运算符)周围使用空格字符时保持一致。

  • 硬连接用户必须提供的输入行数是一个坏主意(并且完全没有必要)。而且你没有处理他/供应少于6行的情况。

答案 1 :(得分:1)

在进行进一步处理之前,您应该删除标点并更改为单个案例。 (注意区域设置和unicode)

将输入分解为单词后,您可以将唯一单词的数量传递给Set并检查集合的大小来计算它们的数量。

答案 2 :(得分:1)

你走了。这个作品。只需阅读评论,你应该能够遵循。

import java.util.Arrays;
import java.util.HashSet;
import javax.swing.JOptionPane;

// Program Counts Words In A Sentence. Duplicates Are Not Counted.
public class WordCount
{
    public static void main(String[]args)
    {
        // Initialize Variables
        String sentence = "";
        int wordCount = 1, startingPoint = 0;


        // Prompt User For Sentence
        sentence = JOptionPane.showInputDialog(null, "Please input a sentence.", "Input Information Below", 2);


        // Remove All Punctuations. To Check For More Punctuations Just Add Another Replace Statement.
        sentence = sentence.replace(",", "").replace(".", "").replace("?", "");


        // Convert All Characters To Lowercase - Must Be Done To Compare Upper And Lower Case Words.
        sentence = sentence.toLowerCase();


        // Count The Number Of Words
        for (int i = 0; i < sentence.length(); i++)
            if (sentence.charAt(i) == ' ')
                wordCount++;


        // Initialize Array And A Count That Will Be Used As An Index
        String[] words = new String[wordCount];
        int count = 0;


        // Put Each Word In An Array
        for (int i = 0; i < sentence.length(); i++)
        {
            if (sentence.charAt(i) == ' ')
            {
                words[count] = sentence.substring(startingPoint,i);
                startingPoint = i + 1;
                count++;
            }
        }


        // Put Last Word In Sentence In Array
        words[wordCount - 1] = sentence.substring(startingPoint, sentence.length());


        // Put Array Elements Into A Set. This Will Remove Duplicates
        HashSet<String> wordsInSet = new HashSet<String>(Arrays.asList(words));


        // Format Words In Hash Set To Remove Brackets, And Commas, And Convert To String
        String wordsString = wordsInSet.toString().replace(",", "").replace("[", "").replace("]", "");


        // Print Out None Duplicate Words In Set And Word Count
        JOptionPane.showMessageDialog(null, "Words In Sentence:\n" + wordsString + " \n\n" +
                                                "Word Count: " + wordsInSet.size(), "Sentence Information", 2);
    }
}

答案 3 :(得分:0)

如果你知道要忽略的标记(;,?,!),你可以做一个简单的String.replace来删除单词中的字符。您可能希望使用String.startsWithString.endsWith来提供帮助

将您的值转换为小写,以便于匹配(String.toLowercase

使用'Set'是一个很好的主意。如果您想知道特定单词出现的次数,您还可以利用某种Map

答案 4 :(得分:0)

  1. 删除所有标点符号
  2. 将所有字符串转换为小写或大写
  3. 将这些字符串放在一组
  4. 获取集合的大小

答案 5 :(得分:0)

  1. 你需要删除标点符号;这是一种方法:Translating strings character by character

  2. 上述内容也可用于规范化案例,但可能还有其他实用程序。

  3. 现在,您描述的所有变体都将转换为相同的字符串,因此可以被识别。正如其他人所建议的那样,设置将是计算不同单词数量的好工具。

答案 6 :(得分:0)

您真正的问题是,您希望拥有一个不同的字数,因此,您应该跟踪已经遇到的字,或者完全从文本中删除它们。

假设您选择了第一个,并将已经遇到的单词存储在列表中,那么您可以检查该列表是否已经看到该单词。

List<String> encounteredWords = new ArrayList<String>();
// continue after that you found out what the word was
if(!encounteredWords.contains(word.toLowerCase()){
    encounteredWords.add(word.toLowerCase());
    wordCount++;
}

但是,锑也提出了一个有趣的评论,他使用Set的属性来查看不同的wordcount是什么。定义一个集合永远不能包含重复项,因此如果您只是添加更多相同的单词,则该集合的大小不会增大。

Set<String> wordSet = new HashSet<String>();
// continue after that you found out what the word was
wordSet.add(word.toLowerCase());
// continue after that you scanned trough all words
return wordSet.size();

答案 7 :(得分:0)

在解析输入字符串时,将其逐字存储在地图数据结构中。只要确保“字”,“字?” “字!”所有内容都与地图中的“word”键一起存储,并在您必须添加到地图时增加单词的计数。