首页 \ 问答 \ C#使用字典(C# using dictionaries)

C#使用字典(C# using dictionaries)

如果要求这种帮助是不好的,我很抱歉...但我不知道还有谁要问。

我有一个任务来读取两个文本文件,并找到第一个文件中10个最长的单词(以及它们重复的次数),它们不存在于第二个文件中。

我目前使用File.ReadAllLines读取两个文件,然后将它们拆分成数组,其中每个元素都是一个单词(删除标点符号)并删除空条目。

我不得不挑选符合要求的词的想法是:创建一个包含字符串Word和int Count的字典。 然后为第一个文件的长度重复一个循环....首先将该元素与整个字典进行比较 - 如果它找到匹配项,则将计数增加1.然后,如果它与任何字典元素都不匹配 - 比较给定元素与第二个文件中的每个元素通过另一个循环,如果它找到匹配的话 - 只要继续阅读第一个文件的下一个元素,如果它没有找到任何匹配项 - 将该单词添加到字典中,并设置数到1。

所以我的第一个问题是:这是否是最有效的方法? (不要忘记我最近才开始学习c#,并且不允许使用linq)

第二个问题:我如何使用字典,因为我发现的大部分结果都非常混乱,我们还没有在大学里见过他们。

我的代码到目前为止:

    // Reading and making all the words lowercase for comparisons
    string punctuation = " ,.?!;:\"\r\n";
    string Read1 = File.ReadAllText("@\\..\\Book1.txt");
    Read1 = Read1.ToLower();
    string Read2 = File.ReadAllText("@\\..\\Book2.txt");
    Read2 = Read2.ToLower();

    //Working with the 1st file
    string[] FirstFileWords = Read1.Split(punctuation.ToCharArray());

    var temp1 = new List<string>();
    foreach (var word in FirstFileWords)
    {
        if (!string.IsNullOrEmpty(word))
            temp1.Add(word);
    }
    FirstFileWords = temp1.ToArray();

    Array.Sort(FirstFileWords, (x, y) => y.Length.CompareTo(x.Length));

    //Working with the 2nd file
    string[] SecondFileWords = Read2.Split(punctuation.ToCharArray());

    var temp2 = new List<string>();
    foreach (var word in SecondFileWords)
    {
        if (!string.IsNullOrEmpty(word))
            temp2.Add(word);
    }
    SecondFileWords = temp2.ToArray();

I'm sorry in advance if it's bad to ask for this sort of help... but I don't know who else to ask.

I have an assignment to read two text files, and find the 10 longest words in the first file (and the amount of times they're repeated) which dont exist in the second file.

I currently read both of the files with File.ReadAllLines then split them into arrays, where every element is a single word (punctuation marks removed as well) and removed empty entries.

The idea I had to pick out the words fitting the requirements was: to make a dictionary containing a string Word and an int Count. Then make a loop repeating for the first file's length.... firstly comparing the element with the entire dictionary - if it finds a match, increase the Count by 1. Then if it doesn't match with any of the dictionary elements - compare the given element with every element in the 2nd file through another loop, if it finds a match - just go on to the next element of the first file, if it doesn't find any matches - add the word to the dictionary, and set Count to 1.

So my first question is: Is this actually the most efficient way to do this? (Don't forget I've only recently started studying c# and am not allowed to use linq)

Second question: How do I work with the dictionary, because most of the results I could find were very confusing, and we have not yet met them at university.

My code so far:

    // Reading and making all the words lowercase for comparisons
    string punctuation = " ,.?!;:\"\r\n";
    string Read1 = File.ReadAllText("@\\..\\Book1.txt");
    Read1 = Read1.ToLower();
    string Read2 = File.ReadAllText("@\\..\\Book2.txt");
    Read2 = Read2.ToLower();

    //Working with the 1st file
    string[] FirstFileWords = Read1.Split(punctuation.ToCharArray());

    var temp1 = new List<string>();
    foreach (var word in FirstFileWords)
    {
        if (!string.IsNullOrEmpty(word))
            temp1.Add(word);
    }
    FirstFileWords = temp1.ToArray();

    Array.Sort(FirstFileWords, (x, y) => y.Length.CompareTo(x.Length));

    //Working with the 2nd file
    string[] SecondFileWords = Read2.Split(punctuation.ToCharArray());

    var temp2 = new List<string>();
    foreach (var word in SecondFileWords)
    {
        if (!string.IsNullOrEmpty(word))
            temp2.Add(word);
    }
    SecondFileWords = temp2.ToArray();

原文:https://stackoverflow.com/questions/40952555
更新时间:2023-07-10 17:07

最满意答案

您可以尝试使用XML模式对象模型来确定兄弟元素之间的顺序。 我在项目中使用它来确定子元素的基数,这在将XML转换为JSON时非常重要,反之亦然。

它需要一些努力才能理解它,但它的效果非常好。

UPDATE

我认为XSOM是Xerces的一部分,或者至少Xerces实现了Post Schema Validation Infoset(PSVI)。 假设您使用模式识别解析器解析输入XML文档,则可以访问PSVI并对其进行分析。 在这里阅读更多。


You could try using the XML Schema Object Model to figure out the order among sibling elements. I have used it in a project to determine the cardinality of child elements, which was important when transforming XML to JSON and vice versa.

It takes some effort to grok it, but it works quite well.

UPDATE

I think XSOM is part of Xerces, or at least Xerces implements Post Schema Validation Infoset (PSVI). Given that you parse the input XML document using a schema aware parser, you can access the PSVI and analyze it. Read more here.

相关问答

更多
  • 查找允许您重新加载依赖项的工具栏按钮。 它应该从引用的模式中清除任何缓存的信息。 不相关,尝试比Indigo更新的版本。 它已经过时了 - 该功能的当前版本是3.5.2。 Look for the toolbar button that allows you to Reload Dependencies. It should flush any cached information from the referenced schemas. Unrelated, try a version newer tha ...
  • 是的,有一个标准的方法。 你正在寻找JAXB 。 Yes, there's a standard way. You're looking for JAXB.
  • 实际上,xsd是xml本身。 其目的是验证另一个xml文档的结构。 xsd对于任何xml都不是强制的,但它确保xml可以用于某些特定目的。 xml只包含适当格式和结构的数据。 Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML coul ...
  • 对于您的要求,我可能会探索CLR集成:使用存储过程或用户定义的函数 ; 如果在您的环境中,您应首先检查CLR集成是否允许。 在这里发帖太过分了; 但是,使用.NET验证XML文档的代码很常见; 只要SQL 2008将会出现,我已经添加到SQL Server在线书籍中的链接就会出现... 总的来说,我认为要实现一个不受SQL Server支持XSD限制的验证,应该依赖CLR集成。 这里描述的SQL服务器上的XSD集合的限制无论如何都可能使许多人朝这个方向发展。 在高容量环境中需要弄清楚一些问题,编译的XSD的 ...
  • 您可以尝试使用XML模式对象模型来确定兄弟元素之间的顺序。 我在项目中使用它来确定子元素的基数,这在将XML转换为JSON时非常重要,反之亦然。 它需要一些努力才能理解它,但它的效果非常好。 UPDATE 我认为XSOM是Xerces的一部分,或者至少Xerces实现了Post Schema Validation Infoset(PSVI)。 假设您使用模式识别解析器解析输入XML文档,则可以访问PSVI并对其进行分析。 在这里阅读更多。 You could try using the XML Schema ...
  • 第1部分 - 验证XML 你可以使用这个javax.xml.validation API。 SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaURL = // The URL to your XML Schema; Schema schema = sf.newSchema(schemaURL); Validator validator = schema.newValid ...
  • 这是一个多部分修复。 我对如何开始工作并不满意,但它确实很有效。 我可以重构,因为我在整个项目中学到了更多。 根据Pankaj的建议:我使用Response作为基础实现了一个派生类。 这还不够,因为我的对象仍在获取基本的Response类,但是因为我需要为每个调用单独的类来完全实现下一步,所以这是必要的。 public class IntegrationSearchReply : Response 然后,我装饰派生类以指定根元素名称。 [XmlRoot(ElementName = "SearchReply ...
  • 您需要为“xs”命名空间使用XNamespace,然后需要使用xsdDoc.Descendants(ns+"element") 。 XNamespace xs = "http://www.w3.org/2001/XMLSchema"; doc.Descendants(xs + "element"). Where(x.Attribute("name") != null && x => x.Attribute("name").Value == "NewDataSet").First(). ...
  • 当您使用XSD.exe工具创建了用于序列化和反序列化Xml文件的类时,您可以使用..将实例写回文件。 序列化 ! ( 存档 ) Stream stream = File.Open(filename, FileMode.Create); XmlFormatter formatter = new XmlFormatter (typeof(XmlObjectToSerialize)); formatter.Serialize(stream, xmlObjectToSerialize); strea ...
  • 应该没问题(只允许整数); 你可能很困惑,因为 不是零; nil xml元素看起来像 (如果已经在更高级别声明了xmlns:xsi,则可以 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)