【发布时间】:2015-04-11 09:49:51
【问题描述】:
我无法处理列表中的元组。 假设我们有一个列表,其中包含很多元组。
simpleTag=[**('samsung', 'ADJ')**, ('user', 'NOUN'), ('huh', 'NOUN'), ('weird', 'NOUN'), (':', '.'), ('MDPai05', 'NOUN'), (':', '.'), ('Samsung', 'NOUN'), ('Electronics', 'NOUN'), ('to', 'PRT'), ('Build', 'NOUN'), ('$', '.'), ('3', 'NUM'), ('Billion', 'NUM'), ('Smartphone', 'NOUN'), ('Plant', 'NOUN'), ('in', 'ADP'), ('Vietnam', 'NOUN'), ('Why', 'NOUN'), ('not', 'ADV'), ('india', 'VERB'), ('?', '.'), ('market', 'NOUN'), ('here', 'ADV'), (':', '.'), (':', '.'), ('//t…I', 'ADJ'), ('have', 'VERB'), ('bricked', 'VERB'), ('an', 'DET'), ('android', 'ADJ'), ('samsung', 'NOUN'), ('galaxy', 'NOUN'), ('player', 'NOUN'), ('yp-g70', 'X'), ('international', 'ADJ'), ('version', 'NOUN'), (',', '.'), ('and', 'CONJ'), ('it', 'PRON'), ('is', 'VERB'), ("n't", 'ADV'), ('recognized', 'VERB'), ('by', 'ADP'), ('PC', 'NOUN'), ('an', 'DET'), ('...', '.'), (':', '.'), ('tomwicky', 'NOUN'), (':', '.'), (':', '.'), ('announces', 'NOUN'), ('partnership', 'NOUN'), ('with', 'ADP'), ('Samsung', 'NOUN'), ('for', 'ADP'), ('wallet', 'NOUN'), ('/', '.'), ('couponing', 'VERB'), ('oms14', 'NOUN'), (':', '.'), ('refrigerator', 'NOUN'), ('(', '.'), ('Spearfish', 'ADJ'), (')', 'NOUN'), ('$', '.'), ('175', 'NUM'), (':', '.'), ('refrigerator', 'NOUN'), ('samsung', 'NOUN'), ('airconditioning', 'VERB'), ('sd', 'NOUN'), ('forsale', 'NOUN'), (':', '.'), ('relaxedharry', 'NOUN'), (':', '.'), ('meanwhile', 'ADV'), ('louis', 'VERB'), ('is', 'VERB'), ('a', 'DET'), **('samsung', 'ADJ')**, ('user', 'NOUN'), ('huh', 'NOUN'), ('weird', 'NOUN'), (':', '.'), ('AmazingRoom', 'NOUN'), (':', '.'), ('if', 'ADP'), ('you', 'PRON'), ('want', 'VERB'), ('a', 'DET'), ('iPhone', 'NOUN'), ('5s', 'NUM'), ('!', '.'), ('*', 'X'), (':', '.'), ('to', 'PRT'), ('win', 'VERB'), ('a', 'DET'), ('Samsung', 'NOUN')]
我想要做的是替换一些元组的值。例如在 simpleTag 中,“samsung”有两个标签:'NOUN' 和 'ADJ'
我正在尝试将“ADJ”替换为“NOUN”
我尝试了以下几个代码,但我不知道为什么它会返回“ADJ”。 上面的例子只是我用 nltk 标记的代码示例。 请让我知道你的想法。
代码1:
[tupleset[:1] + ('NOUN',) for tupleset in simpleTag if word.startswith('samsung')]
代码2:
for (word,tag) in simpleTag:
if word.startswith('samsung'):
tag = 'NOUN'
代码3:
for (word,tag) in simpleTag:
if word.startswith('samsung'):
(word, tag)=(word, 'NOUN')
【问题讨论】:
-
为什么不将元组转换为字典?喜欢stackoverflow.com/questions/3783530/python-tuple-to-dict
-
正如 Dan D 回答的那样,至少在 Code2 和 Code3 中,问题在于您只是在修改本地值。
word和tag是仅存在于for范围内的值。 -
@PabloAntonio 啊哈!感谢您对此发表评论!
-
@向竹元 嗯。谢谢你的评论。我需要考虑一下!