【问题标题】:Counting Words with a list of string[] or string?用字符串 [] 或字符串列表计算单词?
【发布时间】:2018-11-07 05:08:43
【问题描述】:

我试图计算文件中的单词,要么我做一个 string[] 列表并在取出空格时出错,要么我做普通字符串并在拆分字符串部分出错,我也想显示三个最重复的单词,这就是为什么我需要一个所有字符串的列表。

代码如下:

//Reading File

var path = @"D:\Projects\C sharp Course\Working_with_Files\Working_with_Files_1\Text.txt";
List<string> list = new List<string>();
var content = File.ReadAllText(path);
var text = content.Trim();
string[] splitted;

//Splitting String

for (int i = 0; i < text.Length; i++)
{

    splitted = text.Split(',', ' ', '.', '(', ')');          
    list.Add(splitted);
}

//Taking out Whitespaces

for (int i = 0; i < list.Count; i++)
{
    if (string.IsNullOrWhiteSpace(list[i]))
    {
        list.RemoveAt(i);
    }
}

【问题讨论】:

  • list.Add(splitted) 没有意义。 splitted 是一个数组list.Add() 需要一个单个字符串。也许你想要AddRange(),但即便如此,如果你已经有了数组,为什么还要麻烦列表呢?

标签: c# string counting words


【解决方案1】:

对于该文本文件中的每个字母,您将添加所有单词。你不需要for循环。你也不需要第二个循环,因为String.Split 有一个重载:

char[] splitChars = {',', ' ', '.', '(', ')'};
string[] splitted = text.Split(splitChars, StringSplitOptions.RemoveEmptyEntries); 

获取三个最重复单词的子任务:

string[] top3RepeatingWords = splitted   
   .Groupby(w => w)
   .OrderByDescending(g => g.Count())
   .Select(g => g.Key)
   .Take(3)
   .ToArray();

【讨论】:

  • 当我尝试添加 StringSplitOptions 它说:无法转换为字符
  • 啊,没关系,我没有看到你声明为帮助我更好地理解我的代码的 Char,非常感谢
【解决方案2】:

你的循环似乎没有意义,因为每个循环都会做同样的事情:

for (int i = 0; i < text.Length; i++)//You do not use this i!
{
    splitted = text.Split(',', ' ', '.', '(', ')');          
    list.Add(splitted);//Will add the same splitted text each time.
}

我认为您可以删除循环,因为 Split 已经拆分了您的整个文本。

string[] splitted = text.Split(',', ' ', '.', '(', ')');          

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2017-03-22
    • 2023-03-21
    相关资源
    最近更新 更多