如何使用C#计算文本文件中特定单词的出现次数 [英] How to count the occurrences of a particular word in a text file using C#

查看:263
本文介绍了如何使用C#计算文本文件中特定单词的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,我需要阅读其中的所有内容并使用c计算特定单词的所有出现次数#





如何做到这一点

I am having a text file, I need to read all the contents in it and count all the occurrences of a particular word using c#


How to do this

推荐答案

有很多方法可以做到这一点:这个提示显示了一些用于换行符的方法:计算字符串中的行 [ ^ ] - 但整个单词的原理非常相似。



你想看的方式可能是正则表达式:

There are a huge number of ways to do this: this tip shows a number of them for newline characters: Counting Lines in a String[^] - but the principle is very much the same for whole words.

Probably the way you want to look is with a regex:
string text = File.ReadAllText(@"D:\Temp\MyText.txt").ToLower();
int hellos = Regex.Matches(text, @"\bhello\b").Count;



返回hello在文件中作为完整单词出现的次数。


returns the number of times "hello" appears in the file as a complete word.


首先查找句子中的所有单词(使用空格查找单词)并将它们保存在数组中,然后再循环遍历数组以查找匹配的单词。你可能需要多个循环。你可以做到..来吧:)
first find all the words in the sentence( use space to find the words) and keep them in array and again loop through the array to find the matching words. you may need multiple loops. you can make it.. come on :)


这篇关于如何使用C#计算文本文件中特定单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆