2016-03-21 15 views
0

JSON文字列からキーワードを抽出して、その単語のコンテキストを取得しようとしています。私は言葉(例えばパイを提供したいRegex:スペースでアクセント付きの文字を取得

re.findall(regex, string) 

Pythonの

:現在、私のPythonコードがある

JSON

{"1" : "Na casa de meu Pai há muitos aposentos; se não fosse assim, eu lhes teria dito. Vou preparar-lhes lugar."} 

:私の文字列は次のようになります)、キーワードの前後の単語を取得する。私のスクリプトは、キーワードのすべての出現を数え、文脈の単語のリストを作成します。

私の問題は、どのようにアクセント付き文字を空白、コンマ、ドットなどで取得するのですか?何が最善のアプローチですか:希望の文字列を一覧表示するか、不要な文字列を除外しますか?以下のような何か:

([^\"]+)Pai([^\"$]+) 
+2

最良の方法は、代わりに 'JSON'パーサと文字列関数を使うことです。 – Jan

答えて

1

テキスト内の特定の単語の周りの単語、たとえば探索するお手伝いをしますnltk.ConcordanceIndex使用し、その後、json.load()またはjson.loads()経由でJSONデータをロードします。

import nltk 

text = 'Na casa de meu Pai há muitos aposentos; se não fosse assim, eu lhes teria dito. Vou preparar-lhes lugar.' 
tokens = nltk.word_tokenize(text) 

c = nltk.ConcordanceIndex(tokens, key=lambda s: s.lower()) 
result = [] 
for offset in c.offsets('Pai'): 
    result += tokens[offset - 2: offset] 
    result += tokens[offset + 1: offset + 3] 

print(result) 

プリントを['de', 'meu', 'há', 'muitos']

関連する問題