Skip to main content
 首页 » 编程设计

python之抓取匹配词前后的词

2025年02月15日7zhoujg

我正在迈出使用 Python 的第一步,我有一个问题需要解决,我需要使用正则表达式。

我正在解析几行文本,我需要在某个匹配前后抓取 5 个单词。要匹配的词总是相同的,并且行可以多次出现该词。

r"(?i)((?:\S+\s+){0,5})<tag>(\w*)</tag>\s*((?:\S+\s+){0,5})" 

这适用于非常特殊的情况:如果标签之间的术语只出现一次(或者它们之间的间距很好),并且在第一次出现之前有足够的单词。

问题是:

1 - 如果第二次出现在第一次出现的 +5 范围内,则第二次没有 -5,或者第二次被第一次出现。重叠问题?

2 - 如果少于 5 个单词,或者如果您将范围扩大到 7 或 8,它只会跳过第一个出现到第二个或第三个。

所以一行是这样的:

word word word match word word match word word word 

不会被很好地解析。

有没有办法考虑这些问题并使其发挥作用?

提前谢谢大家!

请您参考如下方法:

这可能是您想要的 - 不使用正则表达式

#!/usr/bin/env python 
 
 
 
def find_words(s, count, needle): 
 
  # split the string into a list 
  lst = s.split() 
 
  # get the index of the where the needle is 
  idx = lst.index(needle) 
 
  # s is the start and end of the list you need 
  s = idx -count 
  e = idx +count 
 
  # print the list as slice notation 
  print lst[s:e+1] 
 
 
def find_occurrences_in_list(s, count, needle): 
  # split the string into a list 
  lst = s.split() 
 
  idxList = [i for i, x in enumerate(lst) if x == needle] 
 
  # print idxList 
 
  r = [] 
  for n in idxList: 
    s = n-count 
    e = n+count 
    # append the list as slice notation 
    r.append(" ".join(lst[s:e+1])) 
 
  print r 
 
# the string of words 
mystring1 = "zero one two three four five match six seven eight nine ten eleven" 
# call function to find string, 5 words head & behind, looking for the word "match" 
find_occurrences_in_list(mystring1, 5, "match") 
 
# call function to find string, 3 words head & behind, looking for the word "nation" 
mystring2 = "Four score and seven years ago our fathers brought forth on this continent a new nation conceived in Liberty and dedicated to the proposition" 
find_occurrences_in_list(mystring2, 3, "nation") 
 
mystring3 = "zero one two three four five match six seven match eight nine ten eleven" 
find_occurrences_in_list(mystring3, 2, "match") 
 
 
['one two three four five match six seven eight nine ten'] 
['continent a new nation conceived in Liberty'] 
['four five match six seven', 'six seven match eight nine']