2017-08-10 16 views
1

したがって、段落内の検索語の前後にある10語を抜き出し、すべてを1文に抽出する必要があります。Pythonで特定の単語の周りにいくつかの単語をプルするにはどうすればよいですか?

例:

段落=「飼いイヌ(カニスループスfamiliarisまたはカニスfamiliaris)がオオカミのようなイヌ科動物の一部を形成属カニス(イヌ)のメンバーであり、そして最も広くなります豊富な肉食動物。犬と現存する灰色のオオカミは姉妹分類であり、近代オオカミは最初に飼い馴らされたオオカミと密接に関連しておらず、犬の直接祖先が絶滅したことを意味する。犬は最初に家畜化された種であり、様々な行動、感覚機能、身体的属性のために選択的に繁殖した。

入力

出力

最も広く豊富肉食。犬と現存灰色オオカミは密接

答えて

0

に関係のない現代の狼とあなたがターゲット単語の位置を発見した後、サブストリングを使用して試すことができ、姉妹分類群です。これまで何かをコード化しようとしましたか?

4
​​

出力:

most widely abundant carnivore. The dog and the extant gray wolf are sister taxa, with modern wolves not closely related to 
+0

これは簡単ですが、あなたはgです大量のテキストを使用してパフォーマンスの問題に遭遇する可能性があります。 – WombatPM

2

これはあなたが必要なテキストを抽出役立つ可能正規表現である:私はできませんがまた、Pythonの例

(?:[^ ]+){0,10}wolf(?: [^ ]+){0,10} 

は、同じように行く必要があります今すぐテストしてください:

import re 

t = "The domestic dog (Canis lupus familiaris or Canis familiaris) is a member of genus Canis (canines) that forms part of the wolf-like canids, and is the most widely abundant carnivore. The dog and the extant gray wolf are sister taxa, with modern wolves not closely related to the wolves that were first domesticated, which implies that the direct ancestor of the dog is extinct. The dog was the first domesticated species and has been selectively bred over millennia for various behaviors, sensory capabilities, and physical attributes" 

m = re.search("(?:[^ ]+){0,10}wolf\s(?:[^ ]+){0,10}", t) 

if m: 
    print (m.group(0)) 
関連する問題