簡體   English   中英

Java字數統計程序

[英]Java word count program

我正在嘗試制作一個我已經部分完成的字數計算程序,它給出了正確的結果,但是當我在字符串中輸入空格或多個空格時,字數統計的結果顯示錯誤的結果,因為我正在計算字數根據使用的空間。 如果有一個解決方案,無論有多少空間,我仍然可以得到正確的結果,我需要幫助。 我提到下面的代碼。

public class CountWords 
{
    public static void main (String[] args)
    {

            System.out.println("Simple Java Word Count Program");

            String str1 = "Today is Holdiay Day";

            int wordCount = 1;

            for (int i = 0; i < str1.length(); i++) 
            {
                if (str1.charAt(i) == ' ') 
                {
                    wordCount++;
                } 
            }

            System.out.println("Word count is = " + wordCount);
    }
}
public static void main (String[] args) {

     System.out.println("Simple Java Word Count Program");

     String str1 = "Today is Holdiay Day";

     String[] wordArray = str1.trim().split("\\s+");
     int wordCount = wordArray.length;

     System.out.println("Word count is = " + wordCount);
}

想法是將字符串拆分為出現任意次數的任何空白字符上的單詞。 String 類的 split 函數返回一個包含單詞作為其元素的數組。 打印數組的長度將產生字符串中的單詞數。

兩條路線。 一種方法是使用正則表達式。 您可以在此處找到有關正則表達式的更多信息。 一個好的正則表達式是這樣的 "\w+" 然后計算匹配的數量。

如果你不想走那條路,你可以有一個布爾標志來記住你看到的最后一個字符是否是空格。 如果是,就不要計較了。 所以循環的中心看起來像這樣:

boolean prevCharWasSpace=true;
for (int i = 0; i < str1.length(); i++) 
{
    if (str1.charAt(i) == ' ') {
        prevCharWasSpace=true;
    }
else{
        if(prevCharWasSpace) wordChar++;
        prevCharWasSpace = false;

    }
}

更新
使用拆分技術完全等同於這里發生的事情,但它並不能真正解釋它為什么起作用。 如果我們回到我們的 CS 理論,我們想要構建一個計算單詞的有限狀態自動機 (FSA)。 該 FSA 可能顯示為:
在此處輸入圖像描述
如果您查看代碼,它會准確地實現此 FSA。 prevCharWasSpace 跟蹤我們所處的狀態,而 str1.charAt('i') 決定正在跟隨哪條邊(或箭頭)。 如果使用 split 方法,則在內部構造一個等效於此 FSA 的正則表達式,用於將字符串拆分為數組。

Java 確實有StringTokenizer API,可用於此目的,如下所示。

String test = "This is a test app";
int countOfTokens = new StringTokenizer(test).countTokens();
System.out.println(countOfTokens);

或者

在一行如下

System.out.println(new StringTokenizer("This is a test app").countTokens());

StringTokenizer支持輸入字符串中的多個空格,只計算修剪不必要空格的單詞。

System.out.println(new StringTokenizer("This    is    a test    app").countTokens());

上面的行也打印 5

您可以使用String.split在此處閱讀更多內容)代替 charAt,您將獲得良好的結果。 如果您出於某種原因想使用charAt ,請在計算單詞之前嘗試修剪字符串,這樣您就不會有額外的空間和額外的單詞

我的實現,不使用 StringTokenizer:

Map<String, Long> getWordCounts(List<String> sentences, int maxLength) {
    Map<String, Long> commonWordsInEventDescriptions = sentences
        .parallelStream()
        .map(sentence -> sentence.replace(".", ""))
        .map(string -> string.split(" "))
        .flatMap(Arrays::stream)
        .map(s -> s.toLowerCase())
        .filter(word -> word.length() >= 2 && word.length() <= maxLength)
        .collect(groupingBy(Function.identity(), counting()));
    }

然后,您可以這樣稱呼它,例如:

getWordCounts(list, 9).entrySet().stream()
                .filter(pair -> pair.getValue() <= 3 && pair.getValue() >= 1)
                .findFirst()
                .orElseThrow(() -> 
    new RuntimeException("No matching word found.")).getKey();

也許翻轉方法以返回Map<Long, String>可能會更好。

public class wordCOunt
{
public static void main(String ar[])
{
System.out.println("Simple Java Word Count Program");

    String str1 = "Today is Holdiay Day";

    int wordCount = 1;

    for (int i = 0; i < str1.length(); i++) 
    {
        if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 
    }

    System.out.println("Word count is = " +(str1.length()- wordCount));
}

}

public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");


    int wordCount = 1,count=1;
 BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
            String str2 = "", str1 = "";

            while ((str1 = br.readLine()) != null) {

                    str2 += str1;

            }


    for (int i = 0; i < str2.length(); i++) 
    {
        if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 


        }

    System.out.println("Word count is = " +(wordCount));
}

}

您應該通過考慮其他單詞分隔符來使您的代碼更通用......例如“,”“;” 等等

public class WordCounter{
    public int count(String input){
        int count =0;
        boolean incrementCounter = false;
        for (int i=0; i<input.length(); i++){
            if (isValidWordCharacter(input.charAt(i))){
                incrementCounter = true;
            }else if (incrementCounter){
                count++;
                incrementCounter = false;
            }
        }
        if (incrementCounter) count ++;//if string ends with a valid word
        return count;
    }
    private boolean isValidWordCharacter(char c){
        //any logic that will help you identify a valid character in a word
        // you could also have a method which identifies word separators instead of this
        return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z'); 
    }
}
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;

String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);


//google word counter       
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {   
    wordsMultiset.add(string.toLowerCase());
}

Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
    System.out.println(string+" X "+wordsMultiset.count(string));
}
public static int CountWords(String str){

   if(str.length() == 0)
          return 0;

   int count =0;
   for(int i=0;i< str.length();i++){


      if(str(i) == ' ')
          continue;

      if(i > 0 && str.charAt(i-1) == ' '){
        count++;
      } 

      else if(i==0 && str.charAt(i) != ' '){
       count++;
      }


   }
   return count;

}
    String data = "This world is mine";
    System.out.print(data.split("\\s+").length);

嘗試這個

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class wordcount {
    public static void main(String[] args) {
        String s = "India is my country. I love India";
        List<String> qw = new ArrayList<String>();
        Map<String, Integer> mmm = new HashMap<String, Integer>();
        for (String sp : s.split(" ")) {
            qw.add(sp);
        }
        for (String num : qw) {
            mmm.put(num, Collections.frequency(qw, num));
        }
        System.out.println(mmm);

    }

}

計算總字數或計算總字數而不重復字數

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String test = "I am trying to make make make";
    Pattern p = Pattern.compile("\\w+");
    Matcher m = p.matcher(test);
    HashSet<String> hs =  new HashSet<>();
    int i=0;
    while (m.find()) {
        i++;
        hs.add(m.group());
    }
    System.out.println("Total words Count==" + i);
    System.out.println("Count without Repetation ==" + hs.size());
}

}

輸出 :

總字數==7

不重復計數 ==5

不確定是否有缺點,但這對我有用......

    Scanner input = new Scanner(System.in);
    String userInput = input.nextLine();
    String trimmed = userInput.trim();
    int count = 1;

    for (int i = 0; i < trimmed.length(); i++) {
      if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
        count++;
      }
    }

這可以像使用 split 和 count 變量一樣簡單。

public class SplitString {

    public static void main(String[] args) {
        int count=0;        
        String s1="Hi i love to code";

        for(String s:s1.split(" "))
        {
            count++;
        }
        System.out.println(count);
    }
}
    public class TotalWordsInSentence {
    public static void main(String[] args) {

        String str = "This is sample sentence";
        int NoOfWOrds = 1;

        for (int i = 0; i<str.length();i++){
            if ((str.charAt(i) == ' ') && (i!=0) && (str.charAt(i-1) != ' ')){
                NoOfWOrds++;
            }
        }
         System.out.println("Number of Words in Sentence: " + NoOfWOrds);
    }
}

在這段代碼中,其中的空白不會有任何問題。
只是簡單的 for 循環。 希望這可以幫助...

只計算指定的單詞,如 John、John99、John_John 和 John's only。 根據自己更改正則表達式並僅計算指定的單詞。

    public static int wordCount(String content) {
        int count = 0;
        String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";     
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(content);
        while(matcher.find()) {
            count++;
            System.out.println(matcher.group().trim()); //If want to display the matched words
        }
        return count;
    }

類 HelloWorld {

public static void main(String[] args) {
String str = "User is in for an interview";
int counter=0;
String arrStr[] = str.split(" ");
    for (int i = 0; i< arrStr.length; i++){
        String charStr = arrStr[i];
        for(int j=0; j<charStr.length(); j++) {
            if(charStr.charAt(j) =='i') {
              counter++;
            }
       }
    }
    System.out.println("i " + counter);
}

}

使用split(regex)方法。 結果是一個由regex拆分的字符串數組。

String s = "Today is Holdiay Day";
System.out.println("Word count is = " + s.split(" ").length);

您可以使用此代碼。它可以幫助您:

public static void main (String[] args)
{

   System.out.println("Simple Java Word Count Program");

   String str1 = "Today is Holdiay Day";
   int count=0;
   String[] wCount=str1.split(" ");

   for(int i=0;i<wCount.length;i++){
        if(!wCount[i].isEmpty())
        {
            count++;
        }
   }
   System.out.println(count);
}

您需要逐行讀取文件並將出現在您的行中的空格的多次出現減少為一次出現,然后計算單詞。 以下是一個示例:

public static void main(String... args) throws IOException {   

    FileInputStream fstream = new FileInputStream("c:\\test.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    int wordcount = 0;
    while ((strLine = br.readLine()) != null)   {
        strLine = strLine.replaceAll("[\t\b]", "");
        strLine = strLine.replaceAll(" {2,}", " ");
        if (!strLine.isEmpty()){
            wordcount = wordcount + strLine.split(" ").length;
        }
    }

    System.out.println(wordcount);
    in.close();
}
 public class CountWords 
    {
        public static void main (String[] args)
        {
            System.out.println("Simple Java Word Count Program");
            String str1 = "Today is Holdiay Day";
            int wordCount = 1;
            for (int i = 0; i < str1.length(); i++) 
            {
                if (str1.charAt(i) == ' ' && str1.charAt(i+1)!=' ') 
                {
                    wordCount++;
                } 
            }
            System.out.println("Word count is = " + wordCount));
        }
    }   

這給出了正確的結果,因為如果空間出現兩次或更多,則它不能增加字數。 享受。

完整的程序工作是:

public class main {

    public static void main(String[] args) {

        logicCounter counter1 = new logicCounter();
        counter1.counter("I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.");
    }
}

public class logicCounter {

    public void counter (String str) {

        String str1 = str;
        boolean space= true;
        int i;

        for ( i = 0; i < str1.length(); i++) {

            if (str1.charAt(i) == ' ') {
                space=true;
            } else {
                i++;
            }
        }

        System.out.println("there are " + i + " letters");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM