簡體   English   中英

計算文本文件中特定單詞的頻率

[英]Counting the Frequency of Specific Words in Text File

我有一個文本文件存儲為字符串變量。 文本文件經過處理,因此僅包含小寫單詞和空格。 現在,假設我有一個靜態詞典,它只是特定單詞的列表,我想從文本文件中計算詞典中每個單詞的出現頻率。 例如:

Text file:

i love love vb development although i m a total newbie

Dictionary:

love, development, fire, stone

我希望看到的輸出類似於以下內容,列出了字典單詞及其計數。 如果使編碼更簡單,它也只能列出文本中出現的詞典單詞。

===========

WORD, COUNT

love, 2

development, 1

fire, 0

stone, 0

============

使用正則表達式(例如“ \\ w +”),我可以獲得所有單詞匹配,但是我不知道如何獲取字典中的計數,因此我陷入了困境。 這里的效率至關重要,因為字典很大(約100,000個單詞),文本文件也不小(每個約200kb)。

感謝您的幫助。

您可以通過將字符串分組並將其變成字典來對字符串中的單詞進行計數:

Dictionary<string, int> count =
  theString.Split(' ')
  .GroupBy(s => s)
  .ToDictionary(g => g.Key, g => g.Count());

現在,您只需檢查字典中是否存在單詞,然后查看是否存在計數即可。

var dict = new Dictionary<string, int>();

foreach (var word in file)
  if (dict.ContainsKey(word))
    dict[word]++;
  else
    dict[word] = 1;

使用Groovy regex便利工具,我將按以下步驟操作:

def input="""
    i love love vb development although i m a total newbie
"""

def dictionary=["love", "development", "fire", "stone"]


dictionary.each{
    def pattern= ~/${it}/
    match = input =~ pattern
    println "${it}" + "-"+ match.count
}

嘗試這個。 單詞變量顯然是您的文本字符串。 關鍵字數組是您要計算的關鍵字列表。

對於不在文本中的字典單詞,這不會返回0,但是您指定了這種行為是可以的。 在滿足應用程序要求的同時,這應該為您提供相對良好的性能。

string words = "i love love vb development although i m a total newbie";
string[] keywords = new[] { "love", "development", "fire", "stone" };

Regex regex = new Regex("\\w+");

var frequencyList = regex.Matches(words)
    .Cast<Match>()
    .Select(c => c.Value.ToLowerInvariant())
    .Where(c => keywords.Contains(c))
    .GroupBy(c => c)
    .Select(g => new { Word = g.Key, Count = g.Count() })
    .OrderByDescending(g => g.Count)
    .ThenBy(g => g.Word);

//Convert to a dictionary
Dictionary<string, int> dict = frequencyList.ToDictionary(d => d.Word, d => d.Count);

//Or iterate through them as is
foreach (var item in frequencyList)
    Response.Write(String.Format("{0}, {1}", item.Word, item.Count));

如果您想通過不使用RegEx來實現相同的目的,因為您已表明所有內容都是小寫且由空格分隔,則可以像上面這樣修改上面的代碼:

string words = "i love love vb development although i m a total newbie";
string[] keywords = new[] { "love", "development", "fire", "stone" };

var frequencyList = words.Split(' ')
    .Select(c => c)
    .Where(c => keywords.Contains(c))
    .GroupBy(c => c)
    .Select(g => new { Word = g.Key, Count = g.Count() })
    .OrderByDescending(g => g.Count)
    .ThenBy(g => g.Word);

Dictionary<string, int> dict = frequencyList.ToDictionary(d => d.Word, d => d.Count);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM