我有下面的元组
text =[('Michael', 'PERSON'), ('Jordan', 'PERSON'), ("'s", 'O'), ('legacy', 'O'), ('in', 'O'), ('the', 'O'), ('90', 'O'), ("'s", 'O'), ('shows', 'O'), ('that', 'O'), ('he', 'O'), ('was', 'O'), ('the', 'O'), ('biggest', 'O'), ('player', 'O'), ('ever', 'O'), ('in', 'O'), ('the', 'O'), ('NBA', 'ORGANIZATION'), ('.', 'O')]
原话是“迈克尔乔丹在90年代留下的遗产表明他是NBA有史以来最伟大的球员。”
我需要删除分类为“PERSON”的元素
我就这么做了
new_text = [x for x in text if x[1] != "PERSON"]
sentence= " ".join(x[0] for x in new_text)
print(sentence)
我得到的结果是
's legacy in the 90 's shows that he was the biggest player ever in the NBA .
请注意开头的"'s"
。你知道吗
现在我被卡住了,因为我需要在成为"PERSON"
之前删除以元素为条件的“'s”元素。在这个例子中有2"'s"
,但我只想删除紧跟在"PERSON"
后面的那个。有什么建议吗?你知道吗
谢谢你的意见。你知道吗
你可以使用
range
,如果你找到一个O
,你可以看看后面的:在这里使用简单的for循环要容易得多。请注意,
enumerate
用于检索前一个元素(text[pos-1]
),但是,这只能在前一个元素存在(pos > 0
)时进行。你知道吗执行此脚本将生成以下文本:
legacy in the 90 's shows that he was the biggest player ever in the NBA .
一种方法是使用
zip
循环text
和它的移位版本,并基于以下条件保留字符串:相关问题 更多 >
编程相关推荐