私は、記録する単語の数に柔軟性を持たせるためのパラメータとしてleftとrightを使って、テキスト中の特定の単語(w)のコンテキストを検索する関数を作成しました。正規表現による単語コンテキストの検索
テキスト= [ 'ある' 'Pythonの'、 'ダイナミック'、 '入力された'、 ':
import re def get_context (text, w, left, right): text.insert (0, "*START*") text.append ("*END*") all_contexts = [] for i in range(len(text)): if re.match(w,text[i], 0): if i < left: context_left = text[:i] else: context_left = text[i-left:i] if len(text) < (i+right): context_right = text[i:] else: context_right = text[i:(i+right+1)] context = context_left + context_right all_contexts.append(context) return all_contexts
だから例えば、このようなリストの形式でテキストを持っている場合 'them'、 'but'、 '' '' '' '' '' '' '' '' '' '' '' '' '' '' ' 'want'、 'to'、 'pass'、 'one'、 'thousand'のように、 'パラメータ'、 ''、 '引数'、 'to'、 'your'、 'function'、 'then'、 'can'、 'explicit'、 'define'、 'every' '、'あなた '、'関数 'all'、 'the'、 'the'、 'the'、 'the'、 'and'、 ' 」、 '引数'、 'あなた'、 'パス'、 'に'、 '彼ら'、 'の'、 'あなたは']
機能は、例えば正常に動作します:
get_context(text, "function",2,2)
[['language', 'python', 'functions', 'really', 'care'], ['to', 'your', 'function', 'then', 'you'], ['in', 'your', 'function', 'definition', 'and'], ['and', 'your', 'function', 'will', 'be']]
今、私は次のことをしているテキスト内のすべての単語のコンテキストを使って辞書を構築しようとしています:しかし、私は得ていますこのエラー。
Traceback (most recent call last):
File "<pyshell#32>", line 2, in <module>
d[w] = get_context(text,w,2,2)
File "<pyshell#20>", line 9, in get_context
if re.match(w,text[i], 0):
File "/usr/lib/python3.4/re.py", line 160, in match
return _compile(pattern, flags).match(string)
File "/usr/lib/python3.4/re.py", line 294, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib/python3.4/sre_compile.py", line 568, in compile
p = sre_parse.parse(p, flags)
File "/usr/lib/python3.4/sre_parse.py", line 760, in parse
p = _parse_sub(source, pattern, 0)
File "/usr/lib/python3.4/sre_parse.py", line 370, in _parse_sub
itemsappend(_parse(source, state))
File "/usr/lib/python3.4/sre_parse.py", line 579, in _parse
raise error("nothing to repeat")
sre_constants.error: nothing to repeat
このエラーは分かりません。誰もこれで私を助けることができますか?
さて、それは問題でした。私はこれら2つの* START *と* END *を考えなかった。私はw == text [i]と考えましたが、なぜこれがうまくいかないのか知りたかったのです。ありがとうございます – Wunter