在ruby中拆分句子的更好的正则表达式?
我正在做的是计算一个单词在一堆文本中出现的频率,告诉它出现在哪个句子中,并根据每个单词的频率对结果进行排序。例如: 这就是我到目前为止所做的:在ruby中拆分句子的更好的正则表达式?,ruby,regex,arrays,pattern-matching,Ruby,Regex,Arrays,Pattern Matching,我正在做的是计算一个单词在一堆文本中出现的频率,告诉它出现在哪个句子中,并根据每个单词的频率对结果进行排序。例如: 这就是我到目前为止所做的: File.open('sample_text.txt', 'r') do |f| # open a file named "sample_text.txt" content = f.read # turn the content into a long string # split the string by sentences sentences
File.open('sample_text.txt', 'r') do |f| # open a file named "sample_text.txt"
content = f.read # turn the content into a long string
# split the string by sentences
sentences = content.split(/\.|\?|\!/).each do |es|
es.split(/\W|\s/).each do |w|
#split into individual words
#and for each word, find matched words in the content
end
end
end
问题:
(?<!\be\.g|\bi\.e|\bvs|\bMr|\bMrs|\bDr)(?:\.|\?|\!)(?= |$)
1.
是否有更好的正则表达式用于拆分句子?现在,split(/\.\?\!/)
将Web2.0
作为两句话Web2
和0
2.
有谁能给我一些提示,告诉我如何做返回单词所在的句子数组的部分吗
?
或!
)后加上空格,然后选择性地防止它前面加上某些众所周知的缩写词(例如vs.
或Mr.
或Mrs.
或即或如
)怎么样,也许之后需要一个大写字母
sentences_for_word = Hash.new{ |h,k| h[k] = [] }
sentences.each do |sentence|
words_for_sentence(sentence).each do |word|
sentences_for_word[word] << sentence
end
end
新的{h,k{h[k]=[]}
句子。每一个do |句子|
单词换句子(句子)。每个单词都做|
你可以通过添加一个积极的前瞻性断言来改进你的正则表达式
(?:\.|\?|\!)(?= [^a-z]|$)
看到了吗
(?=[^a-z]|$)
是一个正的loookhead,用于检查前面是否有空格后跟非小写字母或字符串的结尾。这已经给匹配带来了很好的改进
Phrogz的另一个建议(防止在公共approvitions上匹配)不可能在regex中一步完成,因为Ruby不支持lookbehind断言
需要更多步骤才能实现这一点的一种可能性是,在第一步中搜索这些通知,并用占位符替换它们(例如,Mr.与Mr#DOT#),然后在点上拆分后再次替换占位符
只是为了好玩,而不是和Ruby一起工作!后视版本:
(?<!\be\.g|\bi\.e|\bvs|\bMr|\bMrs|\bDr)(?:\.|\?|\!)(?= |$)
(?
查看它。使用单词边界匹配器:str.split(/\W+/)。它适用于大多数文本(尽管我猜它将在“字符”上拆分)。这是一个完整的工作示例
require 'pp'
content = "Meet Mr. Jon. Jon is a computer programmer and lives in Connecticut. Jon is tall. Shouldn't take web 2.0 as two sentences. And this is a new sentence. "
words = {}
content.gsub!(/(Mr)\.|(Mrs)\./,"\\1{dot}").split(/\. |\? |\! /).each_with_index do |sentences, index|
puts "\n#{index}: #{sentences}"
sentences.split(/ +/).each do |word|
word=word.gsub(/{dot}/,"\.").downcase
puts word
words[word]=words[word]||[0,[]]
words[word][0]+=1
words[word][1]<<index
end
end
pp words
你可以根据单词的最小长度过滤掉像“a”这样的单词,然后把它们放在黑名单上。
我很好奇你在做什么,我正在为维基建立一个索引器,因为我无法让Xapian在我的windows/ruby上工作。
Grtz1.但是你怎么能把这些特殊的单词添加到正则表达式中呢?2.谢谢!=)查看[斯坦福语法分析器][1]。它有一个Ruby绑定和类似getSentencesFromString
的方法。[1] :如果使用了正确的格式,则应检查标点符号后是否有两个空格。这就是为什么在标点符号之后应该使用双空格分隔句子的原因之一,而不仅仅是为了美学和做一个体面的人。继续生活,双重空间。靠...过活