【发布时间】:2018-04-10 07:11:12
【问题描述】:
如果单词在列表中,如何在匹配后找到单词? 例如,如果这个词在列表中,我想在 match1 之后找到这个词:
r = ["word1", "word2", "word3"]
如果找到,则返回 word(i)。如果不是,则返回 Unknown。
玩具示例:
Text1 = "This is a match1 for example match1 random text match1 anotherword"
Text2 = "This is a match1 word1 example"
Text3 = "This is an example without word of interest"
如果这个词在列表中 r = ["word1", "word2", "word3"],我想查看 match1 之后的词 预期结果: 对于 Text1,我希望获得 Unknown,对于 Text2 word1,对于 Text3 未知。
到目前为止,我已经设法仅在前两次出现的情况下提取“word1”,但是如果我们有 Text4(如下)我无法提取它,因为我只是要去直到我第二次看到比赛,并且继续使用 if-else 语句继续深入,我不认为这是要走的路,因为 word1 甚至根本不存在。 p>
Text4 = "example match1 example match1 example match1 word1"
def get_labels(text):
q = ["match1"] #Here the idea is to have several, but its the same logic
r = ["word1", "word2", "word3"]
labels = []
for i,item in enumerate(q):
label = text[text.find(q[i])+len(q[i]):].split()[0]
if label in r:
labels.append(label)
else:
texto_temp = text[text.find(q[i])+len(q[i]):]
label2 = texto_temp[texto_temp.find(q[i])+len(q[i]):].split()[0]
labels.append(label2)
return labels
任何想法都会受到赞赏。
【问题讨论】:
-
嵌套的 for 循环?你可以在 for 循环内有一个 for 循环。