Удаление элементов в списке списка с использованием списочных представлений (Python) - PullRequest
1 голос
/ 21 января 2020

У меня есть следующие данные:

[['The',
  'Fulton',
  'County',
  'Grand',
  'Jury',
  'said',
  'Friday',
  'an',
  'investigation',
  'of',
  "Atlanta's",
  'recent',
  'primary',
  'election',
  'produced',
  '``',
  'no',
  'evidence',
  "''",
  'that',
  'any',
  'irregularities',
  'took',
  'place',
  '.'],
 ['The',
  'jury',
  'further',
  'said',
  'in',
  'term-end',
  'presentments',
  'that',
  'the',
  'City',
  'Executive',
  'Committee',
  ',',
  'which',
  'had',
  'over-all',
  'charge',
  'of',
  'the',
  'election',
  ',',
  '``',
  'deserves',
  'the',
  'praise',
  'and',
  'thanks',
  'of',
  'the',
  'City',
  'of',
  'Atlanta',
  "''",
  'for',
  'the',
  'manner',
  'in',
  'which',
  'the',
  'election',
  'was',
  'conducted',
  '.']]

Итак, у меня есть список, который состоит из двух других списков (в моем случае у меня 50000 списков в одном большом списке). Я хочу удалить все знаки препинания и стоп-слова, такие как "the", "a" "of" et c.

Вот что я кодировал:

import string
from nltk.corpus import stopwords
nltk.download('stopwords')

punct = list(string.punctuation)
punct.append("``")
punct.append("''")
stops = set(stopwords.words("english")) 

res = [[word.lower() for word in sentence if word not in punct or word.lower() in not stops] for sentence in dataset] 

Но это возвращает меня тот же список списков, который у меня изначально был. Что не так с моим кодом?

Ответы [ 3 ]

2 голосов
/ 21 января 2020

Поскольку punct и stops не перекрываются, каждое слово не будет ни в одном, ни в другом (или, возможно, в обоих); Вы хотите проверить слова, которых нет в обоих .

2 голосов
/ 21 января 2020

Вы должны использовать and unstead of or:

res = [[word.lower() for word in sentence if word not in punct and word.lower() not in stops] for sentence in dataset]

В противном случае вы получите все элементы, поскольку их не существует по крайней мере в одном из списка stops или punct.

0 голосов
/ 21 января 2020

Предполагая, что будет нормально обновить stops, это альтернатива, которая позволяет избежать двухуровневого понимания

import string
import nltk
from nltk.corpus import stopwords


dataset = [
  ['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an',
   'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election',
   'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities',
   'took', 'place', '.'],
  ['The', 'jury', 'further', 'said', 'in', 'term-end', 'presentments',
   'that', 'the', 'City', 'Executive', 'Committee', ',', 'which', 'had',
   'over-all', 'charge', 'of', 'the', 'election', ',', '``', 'deserves',
   'the', 'praise', 'and', 'thanks', 'of', 'the', 'City', 'of', 'Atlanta',
   "''", 'for', 'the', 'manner',
   'in', 'which', 'the', 'election', 'was', 'conducted', '.']
  ]

nltk.download('stopwords')

punct = list(string.punctuation)
punct.append("``")
punct.append("''")

stops = set(stopwords.words("english"))

# Union of punct and stops
stops.update(punct)
res1 = [[word for word in sentence if word.lower() not in stops]
        for sentence in dataset]

# Alternative solution that avoids an explict 2-level list comprehension
def filter_the(sentence, stops):
    return [word for word in sentence if word.lower() not in stops]


res2 = [filter_the(sentence, stops) for sentence in dataset]


print(res1 == res2)

...