简体   繁体   English

如何计算平均字长

[英]How to calculate average word length

I have tried to calculate the average word length but I keep getting an error appear. 我试图计算平均字长,但我不断出现错误。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Text;

namespace textAnalyser
{
public class Analyser
{
public static void Main()
{
// Values
string myScen;
string newScen = "";
int numbChar = 0;
string userInput;
int countedWords = 0;

//User decsion on how to data is inputted
Console.WriteLine("Enter k for keyboard and r for read from file");
userInput = Convert.ToString(Console.ReadLine());

//If statement, User input is excecuted

if (userInput == "k")
{
// User enters their statment
Console.WriteLine("Enter your statment");
myScen = Convert.ToString(Console.ReadLine());

// Does the scentence end with a full stop?

if (myScen.EndsWith("."))
Console.WriteLine("\n\tScentence Ended Correctly");

else
Console.WriteLine("Invalid Scentence");

Calculating the number of characters in a word 计算单词中的字符数

// Calculate number of characters
foreach (char c in myScen)
{
numbChar++;
if (c == ' ')
continue;

newScen += c;
}
Console.WriteLine("\n\tThere are {0} characters. \n\n\n", numbChar);

// Calculates number of words
countedWords = myScen.Split(' ').Length;
Console.WriteLine("\n\tTherer are {0} words. \n\n\n", countedWords);

This is where I have tried to calculate the average word length //Calculate Average word length 这是我试图计算平均字长//计算平均字长的地方

double averageLength = myScen.Average(w => w.Length);
Console.WriteLine("The average word length is {0} characters.", averageLength);`}

When you call Enumerable LINQ methods such as .Average() or .Where() they operate on the individual elements within the collection. 当您调用Enumerable LINQ方法(如.Average()或.Where())时,它们会对集合中的各个元素进行操作。 A string is a collection of characters, so your myScen.Average() statement is looping through each character of the string, not each word. 字符串是一个字符集合,因此myScen.Average()语句循环遍历字符串的每个字符,而不是每个单词。 Characters are all of length one, so they have no length property. 字符都是长度为1,因此它们没有长度属性。

In order to get access to individual words, you must call .Split(' ') on myScen which gives you a collection (an array to be specific) of strings. 为了能够访问单个单词,您必须在myScen上调用.Split(''),它为您提供字符串的集合(特定的数组)。 Since these strings have length, you can average them and use your final result. 由于这些字符串具有长度,您可以对它们进行平均并使用最终结果。

var countedWords= myScen.Split(' ').Average(n=>n.Length);
Console.WriteLine("\n\tTherer are {0} words. \n\n\n", countedWords);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM