如何获取特定标记前后的单词?

0 投票
3 回答
3062 浏览
提问于 2025-04-18 16:31

我现在在做一个项目,主要是创建基本的语料库数据库和对文本进行分词。但我似乎遇到了一些问题。假设我们有这些内容:

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)

我想过可能有三种情况:这个标记可能是句子的开头,可能是句子的结尾,或者可能是在句子中间出现,所以我用了上面的正则表达式规则。当我运行的时候,我遇到了这些问题:

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\.'

我希望这个问题不是太模糊。

3 个回答

1

正则表达式有时候会很慢(如果没有正确使用的话),而且我发现接受的答案在几个情况下对我没有用。

所以我选择了一个简单粗暴的方法(并不是说这是最好的方法),在这个方法中,关键词可以由几个单词组成:

@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

在关键词前面或后面有空字符串,说明这个关键词是句子中的第一个或最后一个单词。

1

假设我们有一个标记叫做 test。

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

你可以使用前瞻(lookahead)。它不会消耗任何东西,同时也能进行验证。

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

3

我觉得你想要的内容是:

  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']

可以在这里查看演示和逐步解释。

撰写回答