這裏有點蟒蛇/編程新手。訪問元組列表中的元組的第一個元素的範圍
我想從元組列表中訪問指定範圍的元組,但我只想訪問元組範圍中的第一個元素。指定的範圍基於我正在尋找的模式字符串中已被標記並由nltk標記的模式。我的代碼:
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
text = "It is pretty good as far as driveway size is concerned, otherwise I would skip it"
tokenized = word_tokenize(text)
tagged = pos_tag(tokenized)
def find_phrase():
counter = -1
for tag in tagged:
counter += 1
if tag[0] == "as" and tagged[counter+6][0] == "concerned":
print tagged[counter:counter+7]
find_phrase()
打印輸出:
[('as', 'IN'), ('far', 'RB'), ('as', 'IN'), ('driveway', 'NN'), ('size', 'NN'), ('is', 'VBZ'), ('concerned', 'VBN')]
我真正想要的:
['as', 'far', 'as', 'driveway', 'size', 'is', 'concerned']
是否可以修改我的代碼print tagged[counter:counter+7]
行讓我所需的打印輸出?
FYI無論何時你發現自己寫的只是獲取一個循環遞增計數器變量,你或許應該使用'枚舉'而不是。 – roippi