removeWords

Удалите выбранные слова из модели сумки слов или документов

Описание

пример

newDocuments = removeWords(documents,words) удаляет заданные слова из documents. Функция, по умолчанию, является чувствительной к регистру.

пример

newBag = removeWords(bag,words) удаляет заданные слова из модели bag сумки слов. Функция, по умолчанию, является чувствительной к регистру.

newDocuments = removeWords(___,'IgnoreCase',true) удаляет слова, игнорирующие случай с помощью любого из предыдущих синтаксисов.

пример

newDocuments = removeWords(documents,idx) удаляет слова путем определения числовых или логических индексов idx из слов в documents.Vocabulary. Этот синтаксис совпадает с newDocuments = removeWords(documents,documents.Vocabulary(idx)).

пример

newBag = removeWords(bag,idx) удаляет слова путем определения числовых или логических индексов idx из слов в bag.Vocabulary. Этот синтаксис совпадает с newBag = removeWords(bag,bag.Vocabulary(idx)).

Примеры

свернуть все

Удалите слова из массива документов путем введения массива строк слов к removeWords.

Создайте массив маркируемых документов.

documents = tokenizedDocument([
    "an example of a short sentence" 
    "a second short sentence"]);

Удалите слова, "короткие" и "вторые".

words = ["short" "second"];
newDocuments = removeWords(documents,words)
newDocuments = 
  2x1 tokenizedDocument:

    5 tokens: an example of a sentence
    2 tokens: a sentence

Чтобы удалить список по умолчанию слов остановки с помощью деталей языка документов, используйте removeStopWords.

Чтобы удалить пользовательский список слов остановки, используйте removeWords функция. Можно использовать список слов остановки, возвращенный stopWords функционируйте как начальную точку.

Загрузите данные в качестве примера. Файл sonnetsPreprocessed.txt содержит предварительно обработанные версии сонетов Шекспира. Файл содержит один сонет на строку со словами, разделенными пробелом. Извлеките текст из sonnetsPreprocessed.txt, разделите текст в документы в символах новой строки, и затем маркируйте документы.

filename = "sonnetsPreprocessed.txt";
str = extractFileText(filename);
textData = split(str,newline);
documents = tokenizedDocument(textData);

Просмотрите первые несколько документов.

documents(1:5)
ans = 
  5x1 tokenizedDocument:

    70 tokens: fairest creatures desire increase thereby beautys rose might never die riper time decease tender heir might bear memory thou contracted thine own bright eyes feedst thy lights flame selfsubstantial fuel making famine abundance lies thy self thy foe thy sweet self cruel thou art worlds fresh ornament herald gaudy spring thine own bud buriest thy content tender churl makst waste niggarding pity world else glutton eat worlds due grave thee
    71 tokens: forty winters shall besiege thy brow dig deep trenches thy beautys field thy youths proud livery gazed tatterd weed small worth held asked thy beauty lies treasure thy lusty days say thine own deep sunken eyes alleating shame thriftless praise praise deservd thy beautys thou couldst answer fair child mine shall sum count make old excuse proving beauty succession thine new made thou art old thy blood warm thou feelst cold
    65 tokens: look thy glass tell face thou viewest time face form another whose fresh repair thou renewest thou dost beguile world unbless mother fair whose uneard womb disdains tillage thy husbandry fond tomb selflove stop posterity thou art thy mothers glass thee calls back lovely april prime thou windows thine age shalt despite wrinkles thy golden time thou live rememberd die single thine image dies thee
    71 tokens: unthrifty loveliness why dost thou spend upon thy self thy beautys legacy natures bequest gives nothing doth lend frank lends free beauteous niggard why dost thou abuse bounteous largess thee give profitless usurer why dost thou great sum sums yet canst live traffic thy self alone thou thy self thy sweet self dost deceive nature calls thee gone acceptable audit canst thou leave thy unused beauty tombed thee lives th executor
    61 tokens: hours gentle work frame lovely gaze every eye doth dwell play tyrants same unfair fairly doth excel neverresting time leads summer hideous winter confounds sap checked frost lusty leaves quite gone beauty oersnowed bareness every summers distillation left liquid prisoner pent walls glass beautys effect beauty bereft nor nor remembrance flowers distilld though winter meet leese show substance still lives sweet

Создайте список слов остановки начиная с выхода stopWords функция.

customStopWords = [stopWords "thy" "thee" "thou" "dost" "doth"];

Удалите пользовательские слова остановки из документов и просмотрите первые несколько документов.

documents = removeWords(documents,customStopWords);
documents(1:5)
ans = 
  5x1 tokenizedDocument:

    62 tokens: fairest creatures desire increase thereby beautys rose might never die riper time decease tender heir might bear memory contracted thine own bright eyes feedst lights flame selfsubstantial fuel making famine abundance lies self foe sweet self cruel art worlds fresh ornament herald gaudy spring thine own bud buriest content tender churl makst waste niggarding pity world else glutton eat worlds due grave
    61 tokens: forty winters shall besiege brow dig deep trenches beautys field youths proud livery gazed tatterd weed small worth held asked beauty lies treasure lusty days say thine own deep sunken eyes alleating shame thriftless praise praise deservd beautys couldst answer fair child mine shall sum count make old excuse proving beauty succession thine new made art old blood warm feelst cold
    52 tokens: look glass tell face viewest time face form another whose fresh repair renewest beguile world unbless mother fair whose uneard womb disdains tillage husbandry fond tomb selflove stop posterity art mothers glass calls back lovely april prime windows thine age shalt despite wrinkles golden time live rememberd die single thine image dies
    52 tokens: unthrifty loveliness why spend upon self beautys legacy natures bequest gives nothing lend frank lends free beauteous niggard why abuse bounteous largess give profitless usurer why great sum sums yet canst live traffic self alone self sweet self deceive nature calls gone acceptable audit canst leave unused beauty tombed lives th executor
    59 tokens: hours gentle work frame lovely gaze every eye dwell play tyrants same unfair fairly excel neverresting time leads summer hideous winter confounds sap checked frost lusty leaves quite gone beauty oersnowed bareness every summers distillation left liquid prisoner pent walls glass beautys effect beauty bereft nor nor remembrance flowers distilld though winter meet leese show substance still lives sweet

Удалите слова из документов путем введения вектора из числовых индексов к removeWords.

Создайте массив маркируемых документов.

documents = tokenizedDocument([
    "I love MATLAB"
    "I love MathWorks"])
documents = 
  2x1 tokenizedDocument:

    3 tokens: I love MATLAB
    3 tokens: I love MathWorks

Просмотрите словарь documents.

documents.Vocabulary
ans = 1x4 string
    "I"    "love"    "MATLAB"    "MathWorks"

Удалите первые и третьи слова словаря из документов путем определения числовых индексов [1 3].

idx = [1 3];
newDocuments = removeWords(documents,idx)
newDocuments = 
  2x1 tokenizedDocument:

    1 tokens: love
    2 tokens: love MathWorks

В качестве альтернативы можно задать логические индексы.

idx = logical([1 0 1 0]);
newDocuments = removeWords(documents,idx)
newDocuments = 
  2x1 tokenizedDocument:

    1 tokens: love
    2 tokens: love MathWorks

Удалите слова остановки из модели сумки слов путем введения списка слов остановки к removeWords. Остановитесь слова являются словами, такими как "a", и "в" котором обычно удаляются из текста перед анализом.

documents = tokenizedDocument([
    "an example of a short sentence" 
    "a second short sentence"]);
bag = bagOfWords(documents);
newBag = removeWords(bag,stopWords)
newBag = 
  bagOfWords with properties:

          Counts: [2x4 double]
      Vocabulary: ["example"    "short"    "sentence"    "second"]
        NumWords: 4
    NumDocuments: 2

Удалите слова из модели сумки слов путем введения вектора из числовых индексов к removeWords.

Создайте массив маркируемых документов.

documents = tokenizedDocument([
    "I love MATLAB"
    "I love MathWorks"]);
bag = bagOfWords(documents)
bag = 
  bagOfWords with properties:

          Counts: [2x4 double]
      Vocabulary: ["I"    "love"    "MATLAB"    "MathWorks"]
        NumWords: 4
    NumDocuments: 2

Просмотрите словарь bag.

bag.Vocabulary
ans = 1x4 string
    "I"    "love"    "MATLAB"    "MathWorks"

Удалите первые и третьи слова словаря из модели сумки слов путем определения числовых индексов [1 3].

idx = [1 3];
newBag = removeWords(bag,idx)
newBag = 
  bagOfWords with properties:

          Counts: [2x2 double]
      Vocabulary: ["love"    "MathWorks"]
        NumWords: 2
    NumDocuments: 2

В качестве альтернативы можно задать логические индексы.

idx = logical([1 0 1 0]);
newBag = removeWords(bag,idx)
newBag = 
  bagOfWords with properties:

          Counts: [2x2 double]
      Vocabulary: ["love"    "MathWorks"]
        NumWords: 2
    NumDocuments: 2

Входные параметры

свернуть все

Введите документы в виде tokenizedDocument массив.

Введите модель сумки слов в виде bagOfWords объект.

Слова, чтобы удалить в виде вектора строки, вектора символов или массива ячеек из символьных векторов. Если вы задаете words как вектор символов, затем функция обрабатывает его как отдельное слово.

Типы данных: string | char | cell

Индексы слов, чтобы удалить в виде вектора из числовых индексов или вектора из логических индексов. Индексы в idx соответствуйте местоположениям слов в Vocabulary свойство входных документов или модели сумки слов.

Пример: [1 5 10]

Выходные аргументы

свернуть все

Выведите документы, возвращенные как tokenizedDocument массив.

Выведите модель сумки слов, возвращенную как bagOfWords объект.

Введенный в R2017b
Для просмотра документации необходимо авторизоваться на сайте