gpt4 book ai didi

c# - 如何通过删除字符串的非字母来计算词频?

转载 作者:太空宇宙 更新时间:2023-11-03 11:57:57 25 4
gpt4 key购买 nike

我有一个字符串:

var text = @"
I have a long string with a load of words,
and it includes new lines and non-letter characters.
I want to remove all of them and split this text to have one word per line, then I can count how many of each word exist."

删除所有非字母字符,然后将每个单词拆分到一个新行中以便我可以存储和计算每个单词的数量的最佳方法是什么?

var words = text.Split(' ');

foreach(var word in words)
{
word.Trim(',','.','-');
}

我已经尝试过各种方法,例如 text.Replace(characters)whitespace 然后拆分。我已经尝试过 Regex(我不想使用它)。

我还尝试使用 StringBuilder 类从文本(字符串)中获取字符,并且仅在字符是字母 a-z/A-Z 时才附加该字符。

还尝试调用 sb.Replace 或 sb.Remove 我不需要的字符,然后再将它们存储在字典中。但我似乎还是得到了我不想要的字符?

我尝试的每一件事,似乎至少有一个我不想要的角色在那里,并且无法完全弄清楚为什么它不起作用。

谢谢!

最佳答案

使用没有 RegEx 和 Linq 的扩展方法

static public class StringHelper
{
static public Dictionary<string, int> CountDistinctWords(this string text)
{
string str = text.Replace(Environment.NewLine, " ");
var words = new Dictionary<string, int>();
var builder = new StringBuilder();
char charCurrent;
Action processBuilder = () =>
{
var word = builder.ToString();
if ( !string.IsNullOrEmpty(word) )
if ( !words.ContainsKey(word) )
words.Add(word, 1);
else
words[word]++;
};
for ( int index = 0; index < str.Length; index++ )
{
charCurrent = str[index];
if ( char.IsLetter(charCurrent) )
builder.Append(charCurrent);
else
if ( !char.IsNumber(charCurrent) )
charCurrent = ' ';
if ( char.IsWhiteSpace(charCurrent) )
{
processBuilder();
builder.Clear();
}
}
processBuilder();
return words;
}
}

它解析所有字符,拒绝所有非字母,同时创建每个单词的字典,计算出现次数。

测试

var result = text.CountDistinctWords();
Console.WriteLine($"Found {result.Count()} distinct words:");
Console.WriteLine();
foreach ( var item in result )
Console.WriteLine($"{item.Key}: {item.Value}");

您 sample 的结果

Found 36 distinct words:

I: 3
have: 2
a: 2
long: 1
string: 1
with: 1
load: 1
of: 3
words: 1
and: 3
it: 1
includes: 1
new: 1
lines: 1
non: 1
letter: 1
characters: 1
want: 1
to: 2
remove: 1
all: 1
them: 1
split: 1
this: 1
text: 1
one: 1
word: 2
per: 1
line: 1
then: 1
can: 1
count: 1
how: 1
many: 1
each: 1
exist: 1

关于c# - 如何通过删除字符串的非字母来计算词频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58734248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com