【问题标题】:How to count the index while matching匹配时如何计算索引
【发布时间】:2021-09-15 21:55:52
【问题描述】:

目标

我想得到被特定符号包围的单词,例如括号和它们的索引号。

# input and symbol []
A key word is put in parentheses, like these: [keyword] or [key word] 

# output 
keyword (9, 9)
key word (11, 12)

索引号被认为遵循拆分输入句子的列表。

问题

目前的输出主要有两个问题。

  1. 索引计数是由非词库完成的。

  2. 与正则表达式匹配没有达到我的预期。

输出

['A', 'key', 'word', 'is', 'put', 'in', 'parentheses,', 'like', 'these:', '[keyword]', 'or', '[key', 'word]']

keyword] or [key word
(47, 68)

代码

import re

sentence = "A key word is put in parentheses, like these: [keyword] or [key word]"
splitted = sentence.split(' ')
matched = re.finditer("(?<=\[).*(?=\])", sentence)
print(matched)
for w in matched:
    print(w.group())
    print(w.span())

如何修复当前代码以提取目标输出?

【问题讨论】:

  • 你不需要正则表达式。只需split() 短语并检查元素中是否有[
  • 使用这个作为正确的模式:matched = re.finditer("(?

标签: python python-3.x string nsregularexpression


【解决方案1】:

看看这是否有帮助:

import re

sentence = "A key word is put in parentheses, like these: [keyword] or [key word]"
splitted = sentence.split(' ')
matched = re.finditer("(?<=\[)([a-z ]+)(?=\])", sentence)
#print(matched)
for w in matched:
    start = len(sentence[:w.span()[0]-1].split())
    quantity = len(w.group().split()) - 1
    print(w.group(), (start, start + quantity))

我的输出:

keyword (9, 9)
key word (11, 12)

编辑:

你也可以添加这个

sentence = sentence.replace('[', ' [')
sentence = sentence.replace(']', '] ')

为了避免使用 split() 和 len() 计算单词位置时可能出现的错误

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2021-02-06
    • 1970-01-01
    • 2021-02-03
    • 2023-02-09
    相关资源
    最近更新 更多