gpt4 book ai didi

python - for 循环中的lookbehind

转载 作者:行者123 更新时间:2023-12-01 06:13:11 25 4
gpt4 key购买 nike

你好吗?

我有点陷入这个问题,我需要使用 for 循环来查找以 'ing' 结尾且前面有 IN 标签的单词,我来自 C 和 java 背景,这很容易要做,但我还不知道如何在 python 中做到这一点!!

我四处搜寻,这是我认为我需要做的:

for word, tag in list:
if word.endswith('ing'):
//use regular expression here which should look like this '(?<=\bIN\b)ing'

现在当然有一些问题,首先我需要查看前面的标签而不是单词,正则表达式可能是错误的,更重要的是这听起来太复杂了,我在这里遗漏了一些东西吗?只使用以 'ing' 结尾的单词的索引来查看其后面的标签的方法,就像我使用 java 所做的那样??

提前谢谢你,如果这是一个愚蠢的问题,我很抱歉,就像我第二次尝试编写 python 并且仍然生疏=)

编辑:关于我需要做什么的更多解释,这里的一个例子是我试图解决的问题,有时 pos_tag 将 VBG 误认为是名词,所以我需要编写一个给出标记列表的方法(例如 [('Cultivate', 'NNP'), ('peace', 'NN'), ('by', 'IN'), ('observing', ' NN'), ('justice', 'NN')] 纠正此问题并返回 [('Cultivate', 'NNP'), ('peace', 'NN'), ('by', 'IN'), ('observing', 'VBG'), ('justice', 'NN')] ) 注意观察发生了怎样的变化

EDIT2:问题现在解决了,这里是解决方案 def transform(li): 对于 xrange(len(li)) 中的 i: 如果 li[i][0].endswith('ing') 且 i > 0 且 li[i-1][1]: li[i] = (li[i], 'VBG')

谢谢大家的帮助=D很感激

最佳答案

根据您的评论,听起来您想要这样:

def transform(li):
new_li = []
prev_tag = None
for word, tag in li:
if word.endswith('ing') and prev_tag == 'NN':
tag = 'VBG'
new_li += [(word, tag)]
prev_tag = tag
return new_li

您也可以就地执行此操作:

def transform(li):
for i in xrange(len(li)):
if li[i][0].endswith('ing') and i > 0 and li[i-1][1]:
li[i] = (li[i], 'VBG')

请注意,我将 list 重命名为 lilist 是 Python 列表的类型名称,覆盖它是一个坏主意。

关于python - for 循环中的lookbehind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4663486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com