2

フォルダ内のテキストファイルを解析し、特定の検索ワードの周囲にテキストを保存するコードがあります。

ただし、複数の単語に対して同時に機能するようにコードを編集するのに問題があります。検索ワードごとにグループ化するのではなく、テキストファイルごとに結果をグループ化する必要があるため、コード全体をループさせたくありません。

類似した正規表現のバリアントを使用しall_documents.scan("(word1|word2|word3)")たり、正規表現のバリアントを使用したりすることはできません。

    #helper
        def indices text, index, word
        padding = 20
        bottom_i = index - padding < 0 ? 0 : index - padding
        top_i = index + word.length + padding > text.length ? text.length : index +         word.length + padding
        return bottom_i, top_i
    end

    #script
    base_text = File.open("base.txt", 'w')
    Dir::mkdir("summaries") unless File.exists?("summaries")
    Dir.chdir("summaries")

    Dir.glob("*.txt").each do |textfile|
        whole_file = File.open(textfile, 'r').read
        puts "Currently summarizing " + textfile + "..."
        curr_i = 0
        str = nil
        whole_file.scan(/trail/).each do |match|
          if i_match = whole_file.index(match, curr_i)
            top_bottom = indices(whole_file, i_match, match)
            base_text.puts(whole_file[top_bottom[0]..top_bottom[1]] + " : " +         File.path(textfile))
            curr_i += i_match                     
          end
        end
        puts "Done summarizing " + textfile + "."
    end
    base_text.close

何か案は?

4

3 に答える 3

10

あなたはそのために使うことができますRegexp.union()。それはまさにあなたが望むことをします。

あなたのコードでは、それはになります

...
whole_file.scan(Regexp.union(/trail/, /word1/, /word2/, /word3/)).each do |match|
...
于 2013-03-14T22:35:51.487 に答える
1

を使用できますRegexp.unionが、それは部分文字列の一致のみを生成しています。完全な単語を一致させたい場合は、もう少し作業を行う必要があります。私は使用します:

/\b(?:#{ Regexp.union(%w[trail word1 word2 word3]).source })\b/
=> /\b(?:trail|word1|word2|word3)\b/

結果のパターンは、部分文字列を無視して単語全体を見つけます。

foo = /\b(?:#{ Regexp.union(%w[trail word1 word2 word3]).source })\b/
# /\b(?:trail|word1|word2|word3)\b/

words = %w[trail word1 word2 word3]
words.join(' ').scan(foo)
# [
#     [0] "trail",
#     [1] "word1",
#     [2] "word2",
#     [3] "word3"
# ]

words.join.scan(foo)
# []

'trail word1word2 word3'.scan(foo)
# [
#     [0] "trail",
#     [1] "word3"
# ]
于 2013-03-15T03:44:27.820 に答える
0

scan単語 (たとえば/[\w']+/) であり、 のブロック内で、特定の単語のいずれかと一致するかscanどうかを確認する方がよいと思います。$&たまたま興味のないscan単語に一致したとしても、何も問題はありません。無視してください。

于 2013-03-14T22:40:21.470 に答える