使用python查找字符串中索引前面的两个单词

2024-10-05 10:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

给定文本,我想找出发生在未知之前的单词

text="the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"  
items=re.finditer('unknown',text).  #as there are 2 unknown
for i in items:  
   print(i.start()) #to get index of 2 unknown

输出为

19 
81

现在如何分别提取出现在两个未知数之前的单词?
对于第一个未知,我应该得到,女人。
第二个未知的是我应该去美国


Tags: thetext文本items单词atunknownsummer
3条回答

不带re,带itertools.groupbydoc)的版本:

from itertools import groupby

text="the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"

for v, g in groupby(text.split(), lambda k: k=='unknown'):
    if v:
        continue
    l = [*g]
    if len(l) > 1:
        print(l[-2:])

印刷品:

['women', 'marathon']
['usa', 'and']

此表达式可能接近此处所需的表达式:

([\s\S]*?)(\bunknown\b)

测试关于芬德尔

import re

regex = r"([\s\S]*?)(unknown)"

test_str = "the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"

print(re.findall(regex, test_str, re.MULTILINE))

测试重新查找

import re

regex = r"([\s\S]*?)(unknown)"

test_str = "the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

表达式在this demo的右上角面板上解释,如果您希望探索/简化/修改它,在this link中,如果您愿意,您可以一步一步地观察它如何与一些示例输入匹配。你知道吗

短进近:

import re

text = "the women marathon unknown introduced at the summer olympics los angeles usa and unknown won"
matches = re.finditer('(\S+\s+){2}(?=unknown)', text)
for m in matches:
   print(m.group())

输出:

women marathon 
usa and 

相关问题 更多 >

    热门问题