簡體   English   中英

如何獲得特定令牌前后的單詞?

[英]How can I get words after and before a specific token?

我目前在一個項目中工作,該項目只是創建基本的語料庫數據庫並標記文本。 但似乎我陷入了困境。 假設我們有這些東西:

import os, re

texts = []

for i in os.listdir(somedir): # Somedir contains text files which contain very large plain texts.
    with open(i, 'r') as f:
        texts.append(f.read())

現在,我想在標記之前和之后找到單詞。

myToken = 'blue'
found = []
for i in texts:
    fnd = re.findall('[a-zA-Z0-9]+ %s [a-zA-Z0-9]+|\. %s [a-zA-Z0-9]+|[a-zA-Z0-9]+ %s\.' %(myToken, myToken, myToken), i, re.IGNORECASE|re.UNICODE)
    found.extend(fnd)

print myToken
for i in found:
    print '\t\t%s' %(i)

我認為可能存在三種可能性:標記可能會開始句子,標記可能會結束句子或者標記可能出現在句子中,因此我使用了上面的regex規則。 當我跑步時,我遇到了這些事情:

blue
    My blue car # What I exactly want.
    he blue jac # That's not what I want. That must be "the blue jacket."
    eir blue phone # Wrong! > their
    a blue ali # Wrong! > alien
    . Blue is # Okay.
    is blue. # Okay.
    ...

我也嘗試了\\ b \\ w \\ b或\\ b \\ W \\ b東西,但是不幸的是,這些東西沒有返回任何結果,而是返回了錯誤的結果。 我試過了:

'\b\w\b%s\b[a-zA-Z0-9]+|\.\b%s\b\w\b|\b\w\b%s\.'
'\b\W\b%s\b[a-zA-Z0-9]+|\.\b%s\b\W\b|\b\W\b%s\.'

我希望問題不要太模糊。

假設令牌是測試。

        (?=^test\s+.*|.*?\s+test\s+.*?|.*?\s+test$).*

您可以使用先行方式,它不會吃光任何東西,同時也可以進行驗證。

http://regex101.com/r/wK1nZ1/2

我認為您想要的是:

  1. (可選)單詞和空格;
  2. (總是) 'blue'
  3. (可選)一個空格和一個單詞。

因此,一種合適的正則表達式將是:

r'(?i)((?:\w+\s)?blue(?:\s\w+)?)'

例如:

>>> import re
>>> text = """My blue car
the blue jacket
their blue phone
a blue alien
End sentence. Blue is
is blue."""
>>> re.findall(r'(?i)((?:\w+\s)?{0}(?:\s\w+)?)'.format('blue'), text)
['My blue car', 'the blue jacket', 'their blue phone', 'a blue alien', 'Blue is', 'is blue']

請參閱此處的演示和逐令牌說明。

正則表達式有時會很慢(如果未正確實施),而且在某些情況下,接受的答案對我不起作用。

因此,我采用了蠻力解決方案(並不是說這是最好的解決方案),其中關鍵字可以由幾個單詞組成:

@staticmethod
def find_neighbours(word, sentence):
    prepost_map = []

    if word not in sentence:
        return prepost_map

    split_sentence = sentence.split(word)
    for i in range(0, len(split_sentence) - 1):
        prefix = ""
        postfix = ""

        prefix_list = split_sentence[i].split()
        postfix_list = split_sentence[i + 1].split()

        if len(prefix_list) > 0:
            prefix = prefix_list[-1]

        if len(postfix_list) > 0:
            postfix = postfix_list[0]

        prepost_map.append([prefix, word, postfix])

    return prepost_map

關鍵字之前或之后的空字符串分別表示關鍵字是句子中的第一個或最后一個單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM