【问题标题】:Find multiple longest words and count how many times they repeat找出多个最长的单词并计算它们重复的次数
【发布时间】:2018-11-26 08:39:00
【问题描述】:

所以我编写了在两个文本文件中查找最长单词的代码,如果这是第一个文本文件中的唯一单词,它会写入文件。但是我需要在第一个文本文件中找到唯一的单词,然后从这些唯一的单词中找到 10 个最长的单词。然后这 10 个单词从最长到最短排序,并计算它在第一个文本文件中出现的次数。

        string[] LongestWrods(string[] longest1, string[] text2, int longestCount1, out int longestWordText, char[] @char)
    {
        string[] LongestWordsText1 = new string[10];
        longestWordText = 0;
        for (int i = 0; i < longestCount1; i++)
        {
            if (RepeatTimes(text2, longest1[i], @char) == 0)
                LongestWordsText1[longestWordText++] = longest1[i];
        }
        return LongestWordsText1;
    }

【问题讨论】:

  • 这是作业,还是可以使用 Linq?
  • 所以你需要 (A) 在文本中找到唯一的单词,(B) 获取这些唯一单词中最长的单词,(C) 从最长到最短的顺序排列这 10 个单词?听起来像是Hashtable的工作
  • 另外,文本文件中的单词是如何存储的?每行有多个单词吗?还是每行一个字?如果每行有多个单词,分隔符是什么?是空间吗?文件中有多行吗?
  • 要求这么多,哪位有问题?
  • 这是一个作业,我想用 linq 没问题。文本文件:每行有多个单词且有多行

标签: c# word


【解决方案1】:

这边:

class Program
{
    static void Main(string[] args)
    {
        List<string> wordsToCut = File.ReadAllLines("text2.txt").Distinct().ToList();

        List<UniqueWord> uniqueWords = new List<UniqueWord>();

        foreach (string word in File.ReadAllLines("text1.txt"))
        {
            if (wordsToCut.Contains(word) == false)
            {
                UniqueWord uniqueWord = uniqueWords.Where(x => x.Word == word).FirstOrDefault();

                if (uniqueWord != null)
                {
                    uniqueWord.Occurrence++;
                }
                else
                {
                    uniqueWords.Add(new UniqueWord(word));
                }
            }
        }

        uniqueWords = uniqueWords.OrderByDescending(x => x.Word.Length).Take(10).ToList();
    }
}

public class UniqueWord
{
    public string Word { get; set; }
    public int Occurrence { get; set; }

    public UniqueWord(string word)
    {
        Word = word;
        Occurrence = 1;
    }
}

【讨论】:

  • 我忘了说,我有两个文本文件。所以我需要找到那些只出现在 text1 而不是 text2 的单词
  • 已编辑,现在应该可以了
  • 还有一件事......如何使用 StringSplitOptions.RemoveEmptyEntries 并删除所有:''、'.'、'、'、'!'、'?'、':'、';' , '(', ')', '\t' 在两个文件读取?
【解决方案2】:

当然不是最好的选择,但我能得到最快的选择。 largestWordsCount 包含所有 10 个最大的唯一单词以及每个单词在文本中出现的次数。

var text = "The standard Lorem Ipsum passage, standard used standard since the 1500s \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed";
var splittedText = text.Split(' ');
var uniqueWords = new HashSet<string>(splittedText);
var tenLargestWords = uniqueWords.ToList().OrderByDescending(x => x.Length).Take(10);
var largestWordsCount = tenLargestWords.Select(word => new KeyValuePair<string, int>(word, Regex.Matches(text, word).Count)).ToList();               

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多