我有一个散列如下:
{1=>[{content=>"Text of paragraph 1.........."},{content=>"Text of paragraph 2"}]}
上面的散列是在解析文本文件后创建的。键“1”代表第 1 页。它指向一个哈希数组,每个哈希指向一个段落,内容键指向实际文本。
现在我有一个像 [word1,word2,word3] 这样的单词列表。我必须遍历该页面的所有段落内容,并判断哪个段落出现次数最多。
我可以编写自己的代码,对段落中的每个单词进行正则表达式匹配。但我想知道是否有任何强大的字符串匹配库可以解决这个用例(在 C、C++ 甚至 ruby 中)
它只是不是字符串匹配。我需要一个库来提取包含单词列表中单词的最高密度的数据。
最佳答案
这是一个简单的例子,在 ruby
中,用于计算字符串中单词的频率:
def count_words(string)
string
.scan(/[\w']+/) # Treat strings like "don't" as a single word
.each_with_object(Hash.new(0)) do |w,h|
h[w.downcase] += 1
end
end
用法:
word_occurrences = count_words("Hello world! Hello, vipul.")
=> {"hello"=>2, "world"=>1, "vipul"=>1}
你不应该需要第三方库来实现这么简单的东西。
要检查特定单词的出现,只需在散列中查找它:
word_occurrences[word1.downcase]
要获得“最高密度”单词的列表,只需按哈希值排序:
word_occurrences.sort_by {|_word, occurrences| -occurrences}
# Note the negative to make this descending, not ascending
关于c - 查找单词密度最高的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44412354/