2012-05-11 60 views
3

Jep仍在玩Python。提取一個單詞加一個單詞加另外20個(python)

我決定嘗試一下Gensim,這個工具可以找到選定的文字&上下文的主題。

所以我想知道如何在一段文本中找到一個單詞,並將它與它一起提取20個單詞(如在該單詞之前的10個單詞以及該單詞之後的10個單詞),然後將其與其他此類提取一起保存所以Gensim可以在其上運行。

對於我來說,看起來很困難的是找到一種方法來提取前後找到的10個單詞。我之前玩過nltk,只是將文本標記爲單詞或句子,很容易掌握句子。在那個特定的句子之前和之後仍然得到那些單詞或句子似乎很難找出如何去做。

對於那些誰混淆(這裏的凌晨1點,所以我可能會產生混淆),我將用一個例子顯示它:

只要它吃完後,她的血液衝向她的心臟,爲她聽到白雪公主還活着,非常生氣。 「但現在,」 認爲她自己,「我會做出一些將完全摧毀她的東西。」這樣說,她做了一個藝術中毒的梳子,她知道,然後,僞裝自己,她採取了一個古老的遺012形式。她走過七座山丘到七個小矮人的房子, 和[15]敲門聲,喊道:「今天賣好的商品!」

如果我們說這個詞是白雪公主,然後我想爲這部分提取:

她的心臟,因爲她很生氣地聽到白雪公主還活着。 「但是現在,」 以爲她對自己「會前

10字和後白雪公主。

這也是夠酷前後句子白雪公主後改爲獲取句子出現這是否可以在NLTK完成,並且更加容易。

我的意思是什麼最適合我將很高興與兩種解決方案之一,如果有人可以幫助我。

如果這可以用Gensim做太...那很容易,那麼我也會對此感到高興。所以,3種方法中的任何一種都可以,但我只想嘗試一下,看看如何做到這一點,因爲我的腦袋是空白的。

回答

4
strs=""" 
As soon as it had finished, all her blood rushed to her heart, for she was so angry to hear that Snow-White was yet living. "But now," thought she to herself, "will I make something which shall destroy her completely." Thus saying, she made a poisoned comb by arts which she understood, and then, disguising herself, she took the form of an old widow. She went over the seven hills to the house of the seven Dwarfs, and[15] knocking at the door, called out, "Good wares to sell to-day!" 
""" 
spl=strs.split() 

def ans(word): 
    for ind,x in enumerate(spl): 
     if x.strip(",'.!")==word or x.strip(',".!')==word: 
      break  
    print(" ".join(spl[ind-10:ind]+spl[ind:ind+11])) 

ans('Snow-White') 

her heart, for she was so angry to hear that Snow-White was yet living. "But now," thought she to herself, "will 
+0

謝謝正是我一直在尋找!不知道你能找到那樣的索引。 :) – N00programmer

7

該過程被稱爲Keyword in Context (KWIC)

第一步是將您的輸入分成單詞。有很多方法可以使用regular expressions module來做到這一點,例如參見re.splitre.findall

找到某個單詞後,可以使用切片查找前面的10個單詞和之後的10個單詞。

要爲所有單詞構建索引,帶有maxlen的deque可方便實現滑動窗口。

這裏有一個辦法做到這一點有效地利用itertools

from re import finditer 
from itertools import tee, islice, izip, chain, repeat 

def kwic(text, tgtword, width=10): 
    'Find all occurrences of tgtword and show the surrounding context' 
    matches = (mo.span() for mo in finditer(r"[A-Za-z\'\-]+", text)) 
    padded = chain(repeat((0,0), width), matches, repeat((-1,-1), width)) 
    t1, t2, t3 = tee((padded), 3) 
    t2 = islice(t2, width, None) 
    t3 = islice(t3, 2*width, None) 
    for (start, _), (i, j), (_, stop) in izip(t1, t2, t3): 
     if text[i: j] == tgtword: 
      context = text[start: stop] 
      yield context 

print list(kwic(text, 'Snow-White')) 
+0

哇,有趣。儘管如此,我仍在試圖找出如何從這個特定詞彙中減去10加減去。意思就像Ashiwani展示的那樣。這個似乎爲所有單詞建立了一個索引,儘管我只對只帶有「雪白」這個詞的句子感興趣,並且爲那些而不是所有單詞建立了一個索引,但是還是謝謝你的回答(我必須有聲音有點混亂):) – N00programmer

+0

沒問題,這個技術也適用於像「雪白」這樣的單詞,我編輯了答案,在* yield *之前加入了一個* tgtword *測試,並且注意這個答案具有保存標點符號的優點,因爲它知道相對於原始文本的確切開始點和停止點(基於* str.split *的其他解決方案會丟失標點和切點)。 –

相關問題