计算字符串中整个单词的出现次数

本文关键字:单词 字符串 计算 | 更新日期: 2023-09-27 18:00:07

我想找出字符串中特定单词的出现次数。

我在网上搜索过,发现了很多像这样的答案

  • 堆栈溢出应答
  • DotNetPerl的回答

但他们都没有给我准确的结果。

我想要的是:

输入:

I have asked the question in StackOverflow. Therefore i can expect answer here.

"The"关键字的输出:

The keyword count: 2

注意:句子中不应考虑"因此"中的"The"。

基本上,我想匹配整个单词并得到计数。

计算字符串中整个单词的出现次数

像这样尝试

var searchText=" the ";
var input="I have asked the question in StackOverflow. Therefore i can expect answer here.";
var arr=input.Split(new char[]{' ','.'});
var count=Array.FindAll(arr, s => s.Equals(searchText.Trim())).Length;
Console.WriteLine(count);

DOTNETFIDDLE

编辑

对于您的搜索语句

var sentence ="I have asked the question in StackOverflow. Therefore i can expect answer here.";
var searchText="have asked";
char [] split=new char[]{',',' ','.'};
var splitSentence=sentence.ToLower().Split(split);
var splitText=searchText.ToLower().Split(split);
Console.WriteLine("Search Sentence {0}",splitSentence.Length);
Console.WriteLine("Search Text {0}",splitText.Length);
var count=0;
for(var i=0;i<splitSentence.Length;i++){
    if(splitSentence[i]==splitText[0]){
      var index=i;
        var found=true;
        var j=0;
        for( j=0;j<splitText.Length;j++){
          if(splitSentence[index++]!=splitText[j])
          {
              found=false;
              break;
          }
        }
        if(found){
            Console.WriteLine("Index J {0} ",j);
            count++;
            i= index >i ? index-1 : i;
        }
    }
}
Console.WriteLine("Total found {0} substring",count);

DOTNETFIDDLE

一个可能的解决方案是使用Regex:

var count = Regex.Matches(input.ToLower(), String.Format("'b{0}'b", "the")).Count;

try Like this(Way 1)

string SpecificWord = " the ";
            string sentence = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
            int count = 0;
            foreach (Match match in Regex.Matches(sentence, SpecificWord, RegexOptions.IgnoreCase))
            {
                count++;
            }
            Console.WriteLine("{0}" + " Found " + "{1}" + " Times", SpecificWord, count);

或者像这样(方式2)

string SpecificWord = " the ";
string sentence = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
int WordPlace = sentence.IndexOf(SpecificWord);
Console.WriteLine(sentence);
int TimesRep;
for (TimesRep = 0; WordPlace > -1; TimesRep++)
{
    sentence = (sentence.Substring(0, WordPlace) +sentence.Substring(WordPlace +SpecificWord.Length)).Replace("  ", " ");
    WordPlace = sentence.IndexOf(SpecificWord);
}
Console.WriteLine("this word Found " + TimesRep + " time");

您可以使用while循环来搜索第一次出现的索引,然后从找到的索引++位置进行搜索,并在循环结束时设置一个计数器。While循环一直进行到索引==-1。

问题并不是你想象的那么简单;有许多问题需要注意,例如标点符号、字母大小写以及如何识别单词边界等。然而,使用N_Gram概念,我提供了以下解决方案:

1-识别钥匙中有多少单词。将其命名为N

2-提取文本中所有N个连续的单词序列(N_Grams)。

3-计数N_Grams 中密钥的出现

    string text = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
    string key = "the question";
    int gram = key.Split(' ').Count();
    var parts = text.Split(' ');
    List<string> n_grams = new List<string>();
    for (int i = 0; i < parts.Count(); i++)
    {
        if (i <= parts.Count() - gram)
        {
            string sequence = "";
            for (int j = 0; j < gram; j++)
            {
                sequence += parts[i + j] + " ";
            }
            if (sequence.Length > 0)
                sequence = sequence.Remove(sequenc.Count() - 1, 1);
            n_grams.Add(sequence);
        }
    }
    // The result
    int count = n_grams.Count(p => p == key);
}

例如,对于密钥=the question,并将single space视为单词边界,提取以下二进制图:

我有
已询问
询问
问题

中的问题在StackOverflow中
StackOverflow。因此
因此,我
我可以
可以期待
期望答案
在这里回答

并且CCD_ 3在文本中出现的次数不明显:1

这个解决方案应该在字符串所在的位置工作:

var str = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
var numMatches = Regex.Matches(str.ToUpper(), "THE")
    .Cast<Match>()
    .Count(match => 
        (match.Index == 0 || str[match.Index - 1] == ' ') && 
        (match.Index + match.Length == str.Length || 
            !Regex.IsMatch(
                str[match.Index + match.Length].ToString(),
                "[a-zA-Z]")));

NET Fiddle

string input = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
string pattern = @"'bthe'b";
var matches = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
Console.WriteLine(matches.Count);

请参见Regex锚点-"''b"。

像这样尝试

string Text = "I have asked the question in StackOverflow. Therefore i can expect answer here.";
                Text = Text.ToLower();
                Dictionary<string, int> frequencies = null;
                frequencies = new Dictionary<string, int>();
                string[] words = Regex.Split(Text, "''W+");
                foreach (string word in words)
                {
                    if (frequencies.ContainsKey(word))
                    {
                        frequencies[word] += 1;
                    }
                    else
                    {
                        frequencies[word] = 1;
                    }
                }

                foreach (KeyValuePair<string, int> entry in frequencies)
                {
                    string word = entry.Key;
                    int frequency = entry.Value;
                    Response.Write(word.ToString() + "," + frequency.ToString()+"</br>");
                }

要搜索特定单词,请尝试"像这样"。

string Text = "I have asked the question in StackOverflow. Therefore the i can expect answer here.";
        Text = Text.ToLower();
        string searchtext = "the";
        searchtext = searchtext.ToLower();
        string[] words = Regex.Split(Text, "''W+");
        foreach (string word in words)
        {
            if (searchtext.Equals(word))
            {
                count = count + 1;
            }
            else
            {
            }
        }
        Response.Write(count);

Count在字符串中出现整词的可能性很大
例如

第一个:

string name = "pappu kumar sdffnsd sdfnsdkfbsdf sdfjnsd fsdjkn fsdfsd sdfsd pappu kumar";
var res= name.Contains("pappu kumar");
var splitval = name.Split("pappu kumar").Length-1;

第二:

var r = Regex.Matches(name, "pappu kumar").Count;

怎么办(似乎比其他解决方案更高效):

public static int CountOccurences(string haystack, string needle)
{
    return (haystack.Length - haystack.Replace(needle, string.Empty).Length) / needle.Length;
}

尝试一下这种方法也适用于结构化数据。

    var splitStr = inputStr.Split(' ');
    int result_count = splitStr.Count(str => str.Contains("userName"));