3

一致するものを RSS フィードで検索したい 2 語または 3 語句の辞書があります。RSS フィードを取得して処理すると、「ドキュメント」というタイトルのリストの文字列になります。以下の辞書を確認したいのですが、辞書内のフレーズのいずれかがテキスト文字列の一部と一致する場合は、キーの値を返したいと考えています。この問題にアプローチする最善の方法がわかりません。どんな提案でも大歓迎です。

ngramList = {"cash outflows":-1, "pull out":-1,"winding down":-1,"most traded":-1,"steep gains":-1,"military strike":-1,
          "resumed operations":+1,"state aid":+1,"bail out":-1,"cut costs":-1,"alleged violations":-1,"under perform":-1,"more than expected":+1,
         "pay more taxes":-1,"not for sale":+1,"struck a deal":+1,"cash flow problems":-2}
4

2 に答える 2

2

その辞書の数字(-2、-1、+1)は重みであると想定しているため、各ドキュメントの各フレーズを有用にするためにカウントが必要です。

したがって、これを行うための擬似コードは次のようになります。

  1. ドキュメントを行のリストに分割し、次に各行を単語のリストに分割します。
  2. 次に、行内の各単語をループし、行内を前後にループして、さまざまなフレーズを生成します。
  3. 各フレーズが生成されると、フレーズと出現回数を含むグローバル ディクショナリを保持します。

これは、ドキュメント内の各フレーズの数を見つける単純なケースのコードです。これは、あなたがやろうとしていることのようです:

text = """
I have a dictionary of 2 and 3 word phrases that I want to search in rss feeds for a match. 

I grab   the rss feeds, process them and they end up as a string IN a list entitled "documents". 
I want to check the dictionary below and if any of the phrases in the dictionary match part of a string of text I want to return the values for the key. 
I am not sure about the best way to approach this problem. Any suggestions would be greatly appreciated.
"""

ngrams = ["grab the rss", "approach this", "in"]

import re

counts = {}
for ngram in ngrams:
    words = ngram.rsplit()
    pattern = re.compile(r'%s' % "\s+".join(words),
        re.IGNORECASE)
    counts[ngram] = len(pattern.findall(text))

print counts

出力:

{'grab the rss': 1, 'approach this': 1, 'in': 5}
于 2013-10-06T20:08:51.890 に答える