exponenta event banner

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», «the» и «in», которые обычно удаляются из текста перед анализом.

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