[英]Delete item in a list within a list
stopwords
是字符串列表, tokentext
是字符串列表列表。 (每個列表是一個句子,列表是一個文本文檔)。
我只是試圖將tokentext
中的所有字符串都取出來,這些字符串也出現在stopwords
。
for element in tokentext:
for word in element:
if(word.lower() in stopwords):
element.remove(word)
print(tokentext)
我希望有人指出我遍歷列表時的一些基本缺陷。
這是一個失敗的數據集: http : //pastebin.com/p9ezh2nA
在迭代列表時更改列表總是會產生問題。 嘗試類似以下內容:
stopwords = ["some", "strings"]
tokentext = [ ["some", "lists"], ["of", "strings"] ]
new_tokentext = [[word for word in lst if word not in stopwords] for lst in tokentext]
# creates a new list of words, filtering out from stopwords
或使用filter
:
new_tokentext = [list(filter(lambda x: x not in stopwords, lst)) for lst in tokentext]
# the call to `list` here is unnecessary in Python2
您可以做一些簡單的事情,例如:
for element in tokentext:
if element in stop words:
stopwords.remove(element)
有點像您的,但是沒有多余的for循環。 但是我不確定這是否可行,或者這是否是您要實現的目標,但這是一個主意,希望對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.