1

我在 moy 代码中有一个元组:

('H', 'NNP')

这是代码:

# -*- coding: utf-8 -*-
from nltk.corpus import wordnet as wn
from nltk import pos_tag
import nltk
syno =[]


sentence = '''His father suggested he study to become a parson instead, but Darwin was far more inclined to study natural history.DarwinDar·win (där'wĭn),Charles Robert.1809-1882.British naturalist who revolutionized the study of biology with his theory ofevolutionbased on natural selection
Like several scientists before him, Darwin believed all the life on earth evolved (developed gradually) over millions of years from a few common ancestors.'''
sent = pos_tag(sentence)

alpha = [s for s in sent if s[1] == 'NNP']
for i in range(0,len(alpha)-1):
    print alpha[i] #return the tuple

我只想从中删除 H 。我该怎么做?

4

3 回答 3

1

元组是不可变的,所以你必须创建一个新的:

>>> t = ('H', 'NNP')
>>> tuple(x for x in t if x != 'H')
('NNP',)
>>> z = tuple(x for x in t if x == 'H')
>>> z
('H',)
>>> z[0]
'H'
>>>
于 2013-08-15T15:55:10.367 回答
0
>>> x = ('H', 'NNP')
>>> x = tuple(list(x)[1:])
>>> x
('NNP',)
于 2013-08-15T16:16:24.003 回答
0

你不能改变元组,它们是“不可变的”

如果您改为使用可变数据结构(如列表),则可以更改它们

>>>a = ['H', 'NNP']
>>>a[0] = 'J'          # this changes the 'H' to a 'J'
>>>print a
['J', 'NNP']

如果您出于某种原因需要将一个转换为另一个,您可以这样做myTuple = tuple(myList)myList = list(myTuple)

于 2013-08-15T16:05:31.917 回答