Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字典允许看似相同的键_C#_Dictionary - Fatal编程技术网

C#字典允许看似相同的键

C#字典允许看似相同的键,c#,dictionary,C#,Dictionary,我创建了一个字典,创建了读取txt文件的代码,并将文件中的每个单词输入字典 //Set up OpenFileDialog box, and prompt user to select file to open DialogResult openFileResult; OpenFileDialog file = new OpenFileDialog() ; file.Filter = "txt files (*.txt)|*.txt

我创建了一个字典,创建了读取txt文件的代码,并将文件中的每个单词输入字典

        //Set up OpenFileDialog box, and prompt user to select file to open
        DialogResult openFileResult;
        OpenFileDialog file = new OpenFileDialog() ;
        file.Filter = "txt files (*.txt)|*.txt";
        openFileResult = file.ShowDialog();

        if (openFileResult == DialogResult.OK)
        {
            //If user selected file successfully opened

            //Reset form
            this.Controls.Clear();
            this.InitializeComponent();

            //Read from file, split into array of words
            Stream fs = file.OpenFile();
            StreamReader reader;
            reader = new StreamReader(fs);
            string line = reader.ReadToEnd();
            string[] words = line.Split(' ', '\n');

            //Add each word and frequency to dictionary
            foreach (string s in words)
            {
                AddToDictionary(s);
            }

            //Reset variables, and set-up chart
            ResetVariables();
            ChartInitialize();

            foreach (string s in wordDictionary.Keys)
            {
                //Calculate statistics from dictionary
                ComputeStatistics(s);

                if (dpCount < 50)
                {
                    AddToGraph(s);
                }
            }

            //Print statistics
            PrintStatistics();
        }
此程序正在读取的文本文件是:

To be or not to be that is the question
Whether tis nobler in the mind to suffer
The slings and arrows of outrageous fortune
Or to take arms against a sea of troubles
And by opposing end them To die to sleep
No more and by a sleep to say we end
The heartache and the thousand natural shocks
That flesh is heir to Tis a consummation
Devoutly to be wished To die to sleep
To sleep perchance to dream ay theres the rub
For in that sleep of death what dreams may come
When we **have** shuffled off this mortal coil
Must give us pause Theres the respect
That makes calamity of so long life
For who would bear the whips and scorns of time
The oppressors wrong the proud mans contumely
The pangs of despised love the laws delay
The insolence of office and the spurns
That patient merit of th unworthy takes
When he himself might his quietus make
With a bare bodkin Who would fardels bear
To grunt and sweat under a weary life
But that the dread of something after death
The undiscovered country from whose bourn
No traveller returns puzzles the will
And makes us rather bear those ills we **have**
Than fly to others that we know not of
Thus conscience does make cowards of us all
And thus the native hue of resolution
Is sicklied oer with the pale cast of thought
And enterprise of great pitch and moment
With this regard their currents turn awry
And lose the name of action Soft you now
The fair Ophelia Nymph in thy orisons
Be all my sins remembered
我遇到的问题是“have”一词在字典里出现了两次。我知道字典不会出现这种情况,但出于某种原因,它出现了两次。有人知道为什么会发生这种情况吗?

如果您运行:

var sb = new StringBuilder();
sb.AppendLine("test which");
sb.AppendLine("is a test");
var words = sb.ToString().Split(' ', '\n').Distinct();
在调试器中检查
,显示“test”的某些实例已获得
\r
,这是由于两字节CRLF行终止符造成的,该终止符未被拆分处理

若要修复,请将拆分更改为:

Split(new[] {" ", Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

如果您想支持多种语言,将文本拆分为单词通常是一个困难的解决方案。正则表达式通常比基本的
String.Split
更好地处理解析

也就是说,在你的例子中,你可以选择“新行”的变体作为单词的一部分,你也可以选择不间断空格

以下代码将选择比您当前的
.Split
更好的单词,以了解更多信息-

此外,您应该确保字典不区分大小写,如下所示(根据您的需要选择comparer,也有区域性识别):


我倾向于更改以下代码:

        //Read from file, split into array of words
        Stream fs = file.OpenFile();
        StreamReader reader;
        reader = new StreamReader(fs);
        string line = reader.ReadToEnd();
        string[] words = line.Split(' ', '\n');

        //Add each word and frequency to dictionary
        foreach (string s in words)
        {
            AddToDictionary(s);
        }
为此:

wordDictionary =
    File
        .ReadAllLines(file)
        .SelectMany(x => x.Split(new [] { ' ', }, StringSplitOptions.RemoveEmptyEntries))
        .Select(x => x.ToLower())
        .GroupBy(x => x)
        .ToDictionary(x => x.Key, x => x.Count());

这完全避免了行尾的问题,还有一个额外的优点,就是它不会留下任何未经处理的流。

检查“have”条目前后是否有不可见的空格。@EricJ。如果我已将分隔符设置为“”和“\n”,这会有关系吗?请在添加到之前删除单词中的所有空格dictionary@TRids,您可能还有新行中的
\r
。您需要修剪所有空白。@trid在处理类似情况时,我通常会在我的键中添加trim,即string wordLower=s.ToLower().trim();以防像Eric J。
 var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
        //Read from file, split into array of words
        Stream fs = file.OpenFile();
        StreamReader reader;
        reader = new StreamReader(fs);
        string line = reader.ReadToEnd();
        string[] words = line.Split(' ', '\n');

        //Add each word and frequency to dictionary
        foreach (string s in words)
        {
            AddToDictionary(s);
        }
wordDictionary =
    File
        .ReadAllLines(file)
        .SelectMany(x => x.Split(new [] { ' ', }, StringSplitOptions.RemoveEmptyEntries))
        .Select(x => x.ToLower())
        .GroupBy(x => x)
        .ToDictionary(x => x.Key, x => x.Count());