擅长:python、mysql、java
<p>在这里使用简单的for循环要容易得多。请注意,<code>enumerate</code>用于检索前一个元素(<code>text[pos-1]</code>),但是,这只能在前一个元素存在(<code>pos > 0</code>)时进行。你知道吗</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
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')]
new_text = []
for pos, (word, type_) in enumerate(text):
if type_ == "PERSON":
# we ignore words of type PERSON
continue
if word == "'s" and pos > 0 and text[pos-1][1] == "PERSON":
# ignore 's if the previous word was of type PERSON
continue
new_text.append((word, type_))
sentence= " ".join(x[0] for x in new_text)
print(sentence)shows
</code></pre>
<p>执行此脚本将生成以下文本:<br/>
<code>legacy in the 90 's shows that he was the biggest player ever in the NBA .</code></p>