如何在列表中添加唯一单词及其出现次数
How to add unique words and their number of occurrences in a List
我正在尝试用 C# 编写一个程序,该程序将从文件中读取文本并计算每个唯一单词出现的次数,并跟踪文件中的单词。例如,在字符串 "this is my text and this is it" 中,我会得到:
这个 - 2
是 - 2
我的 - 1
文本1
和 - 1
它 - 1
有没有简单的方法可以做到这一点?我是 C# 的新手,我还没有看到太多我通过搜索完全理解的东西。
编辑:
这是我试过的代码。似乎我返回的列表一遍又一遍地包含文件中的最后一个单词,并且计数已关闭。另外,即使我尝试去掉大写字母和句号,它们仍然会出现。
public override List<WordEntry> GetWordCount()
{
List<WordEntry> words = new List<WordEntry>();
WordEntry wordEntry = new WordEntry();
string[] tokens = null;
string line, temp;
int count = 0, index = 0;
while ((line = input.ReadLine()) != null)
{
temp = Regex.Replace(line, @"\([0-9].\)", "");
temp.ToLower();
tokens = temp.Split(null);
for (int i = 0; i < tokens.Length; i++)
{
wordEntry.Word = tokens[i];
foreach (var word in tokens)
{
if (word == tokens[i])
count++;
}//end foreach
wordEntry.WordCount = count;
words.Add(wordEntry);
}//end for
}//end while
return words;
}//end GetWordCount
您可以使用分组,只需拆分您的模板并按单词分组:
var template = "this is my text and this is it";
var result = template.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(grp => grp)
.Select(grp => new {Word = grp.Key , Count= grp.Count()})
.ToList();
第一步是查找 StreamReader class...StreamReader class 将用于读取文本文件...然后将文本文件的每一行拆分为一个 String []...在你做到这一点之后..你可以使用 foreach 循环遍历 String[] 并计算一个单词在数组中出现的次数。
我正在尝试用 C# 编写一个程序,该程序将从文件中读取文本并计算每个唯一单词出现的次数,并跟踪文件中的单词。例如,在字符串 "this is my text and this is it" 中,我会得到:
这个 - 2 是 - 2 我的 - 1 文本1 和 - 1 它 - 1
有没有简单的方法可以做到这一点?我是 C# 的新手,我还没有看到太多我通过搜索完全理解的东西。
编辑:
这是我试过的代码。似乎我返回的列表一遍又一遍地包含文件中的最后一个单词,并且计数已关闭。另外,即使我尝试去掉大写字母和句号,它们仍然会出现。
public override List<WordEntry> GetWordCount()
{
List<WordEntry> words = new List<WordEntry>();
WordEntry wordEntry = new WordEntry();
string[] tokens = null;
string line, temp;
int count = 0, index = 0;
while ((line = input.ReadLine()) != null)
{
temp = Regex.Replace(line, @"\([0-9].\)", "");
temp.ToLower();
tokens = temp.Split(null);
for (int i = 0; i < tokens.Length; i++)
{
wordEntry.Word = tokens[i];
foreach (var word in tokens)
{
if (word == tokens[i])
count++;
}//end foreach
wordEntry.WordCount = count;
words.Add(wordEntry);
}//end for
}//end while
return words;
}//end GetWordCount
您可以使用分组,只需拆分您的模板并按单词分组:
var template = "this is my text and this is it";
var result = template.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(grp => grp)
.Select(grp => new {Word = grp.Key , Count= grp.Count()})
.ToList();
第一步是查找 StreamReader class...StreamReader class 将用于读取文本文件...然后将文本文件的每一行拆分为一个 String []...在你做到这一点之后..你可以使用 foreach 循环遍历 String[] 并计算一个单词在数组中出现的次数。