[英]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$).*
您可以使用先行方式,它不会吃光任何东西,同时也可以进行验证。
我认为您想要的是:
'blue'
; 因此,一种合适的正则表达式将是:
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.