我有一些要清理的文本数据。此数据的不良特征之一是由特定标记分隔的重复标记。我试图找到一种方法来 (1) 在文本中识别该标记,以及 (2) 删除其中一个重复项。
玩具示例:
word_list = ['this','is','a','!!','a','list','I','want','to','clean']
在这里,有两个重复的 'a' 标记,由标记 '!!' 分隔。我试图找到最有效的方法来迭代列表,如下所示
#pseudo
for word in word_list
if word == "!!":
if word[at word-1] == word[at word+1] # compare words either side of the "!!" marker
del word[at word+1] # removing the duplicate
del word # removing the "!!" marker
output = ['this','is','a','list','I','want','to','clean']
我已经尝试了几种涉及该enumerate
功能的方法,但似乎无法让它发挥作用。
使用您的逻辑和enumerate
功能:
word_list = ['this','is','a','!!','a','list','I','want','to','clean']
for i, word in enumerate(word_list):
if word == "!!":
if word_list[i-1] == word_list[i+1]:
word_list[i+1] = ""
word_list[i] = ""
print ([x for x in word_list if x])
输出:
['this', 'is', 'a', 'list', 'I', 'want', 'to', 'clean']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句