В этом примере показано, как создать функцию очистки и предварительной обработки текстовых данных для анализа.
Текстовые данные могут быть большими и содержать много шума, что негативно влияет на статистический анализ. Например, текстовые данные могут содержать следующее:
Вариации в случае, например «новый» и «новый»
Вариации в словоформах, например «ходить» и «ходить»
Слова, которые добавляют шум, например стоп-слова, такие как «the» и «of»
Знаки препинания и специальные символы
Теги HTML и XML
Эти облака слов иллюстрируют анализ частоты слов, применяемый к некоторым необработанным текстовым данным из производственных отчетов, и предварительно обработанную версию тех же текстовых данных.

Загрузите данные примера. Файл factoryReports.csv содержит заводские отчеты, включая текстовое описание и категориальные метки для каждого события.
filename = "factoryReports.csv"; data = readtable(filename,'TextType','string');
Извлеките текстовые данные из поля Descriptionи данные метки из поля Category.
textData = data.Description; labels = data.Category; textData(1:10)
ans = 10×1 string
"Items are occasionally getting stuck in the scanner spools."
"Loud rattling and banging sounds are coming from assembler pistons."
"There are cuts to the power when starting the plant."
"Fried capacitors in the assembler."
"Mixer tripped the fuses."
"Burst pipe in the constructing agent is spraying coolant."
"A fuse is blown in the mixer."
"Things continue to tumble off of the belt."
"Falling items from the conveyor belt."
"The scanner reel is split, it will soon begin to curve."
Создание массива маркированных документов.
cleanedDocuments = tokenizedDocument(textData); cleanedDocuments(1:10)
ans =
10×1 tokenizedDocument:
10 tokens: Items are occasionally getting stuck in the scanner spools .
11 tokens: Loud rattling and banging sounds are coming from assembler pistons .
11 tokens: There are cuts to the power when starting the plant .
6 tokens: Fried capacitors in the assembler .
5 tokens: Mixer tripped the fuses .
10 tokens: Burst pipe in the constructing agent is spraying coolant .
8 tokens: A fuse is blown in the mixer .
9 tokens: Things continue to tumble off of the belt .
7 tokens: Falling items from the conveyor belt .
13 tokens: The scanner reel is split , it will soon begin to curve .
Чтобы улучшить лемматизацию, добавьте часть речевых данных в документы с помощью addPartOfSpeechDetails. Используйте addPartOfSpeech функция перед удалением стоп-слов и лемматизации.
cleanedDocuments = addPartOfSpeechDetails(cleanedDocuments);
Такие слова, как «a», «and», «to» и «the» (известные как стоп-слова) могут добавлять шум к данным. Удалить список стоп-слов с помощью removeStopWords функция. Используйте removeStopWords перед использованием normalizeWords функция.
cleanedDocuments = removeStopWords(cleanedDocuments); cleanedDocuments(1:10)
ans =
10×1 tokenizedDocument:
7 tokens: Items occasionally getting stuck scanner spools .
8 tokens: Loud rattling banging sounds coming assembler pistons .
5 tokens: cuts power starting plant .
4 tokens: Fried capacitors assembler .
4 tokens: Mixer tripped fuses .
7 tokens: Burst pipe constructing agent spraying coolant .
4 tokens: fuse blown mixer .
6 tokens: Things continue tumble off belt .
5 tokens: Falling items conveyor belt .
8 tokens: scanner reel split , soon begin curve .
Лемматизировать слова с помощью normalizeWords.
cleanedDocuments = normalizeWords(cleanedDocuments,'Style','lemma'); cleanedDocuments(1:10)
ans =
10×1 tokenizedDocument:
7 tokens: items occasionally get stuck scanner spool .
8 tokens: loud rattle bang sound come assembler piston .
5 tokens: cut power start plant .
4 tokens: fry capacitor assembler .
4 tokens: mixer trip fuse .
7 tokens: burst pipe constructing agent spray coolant .
4 tokens: fuse blow mixer .
6 tokens: thing continue tumble off belt .
5 tokens: fall item conveyor belt .
8 tokens: scanner reel split , soon begin curve .
Удалите пунктуацию из документов.
cleanedDocuments = erasePunctuation(cleanedDocuments); cleanedDocuments(1:10)
ans =
10×1 tokenizedDocument:
6 tokens: items occasionally get stuck scanner spool
7 tokens: loud rattle bang sound come assembler piston
4 tokens: cut power start plant
3 tokens: fry capacitor assembler
3 tokens: mixer trip fuse
6 tokens: burst pipe constructing agent spray coolant
3 tokens: fuse blow mixer
5 tokens: thing continue tumble off belt
4 tokens: fall item conveyor belt
6 tokens: scanner reel split soon begin curve
Удалите слова, содержащие не более 2 символов, и слова, содержащие не менее 15 символов.
cleanedDocuments = removeShortWords(cleanedDocuments,2); cleanedDocuments = removeLongWords(cleanedDocuments,15); cleanedDocuments(1:10)
ans =
10×1 tokenizedDocument:
6 tokens: items occasionally get stuck scanner spool
7 tokens: loud rattle bang sound come assembler piston
4 tokens: cut power start plant
3 tokens: fry capacitor assembler
3 tokens: mixer trip fuse
6 tokens: burst pipe constructing agent spray coolant
3 tokens: fuse blow mixer
5 tokens: thing continue tumble off belt
4 tokens: fall item conveyor belt
6 tokens: scanner reel split soon begin curve
Создание модели сумки слов.
cleanedBag = bagOfWords(cleanedDocuments)
cleanedBag =
bagOfWords with properties:
Counts: [480×352 double]
Vocabulary: [1×352 string]
NumWords: 352
NumDocuments: 480
Удалите слова, не появляющиеся более двух раз в модели сумки слов.
cleanedBag = removeInfrequentWords(cleanedBag,2)
cleanedBag =
bagOfWords with properties:
Counts: [480×163 double]
Vocabulary: [1×163 string]
NumWords: 163
NumDocuments: 480
Некоторые шаги предварительной обработки, такие как removeInfrequentWords оставляет пустые документы в модели мешка слов. Чтобы гарантировать отсутствие пустых документов в модели мешка слов после предварительной обработки, используйте removeEmptyDocuments как последний шаг.
Удалить пустые документы из модели мешка слов и соответствующие этикетки из labels.
[cleanedBag,idx] = removeEmptyDocuments(cleanedBag); labels(idx) = []; cleanedBag
cleanedBag =
bagOfWords with properties:
Counts: [480×163 double]
Vocabulary: [1×163 string]
NumWords: 163
NumDocuments: 480
Может быть полезно создать функцию, которая выполняет предварительную обработку, чтобы можно было подготовить различные коллекции текстовых данных одним и тем же способом. Например, можно использовать функцию для предварительной обработки новых данных с использованием тех же шагов, что и учебные данные.
Создайте функцию, которая маркирует и предварительно обрабатывает текстовые данные, чтобы их можно было использовать для анализа. Функция preprocessText, выполняет следующие шаги:
Маркировка текста с помощью tokenizedDocument.
Удалите список стоп-слов (например, «and», «of» и «the»), используя removeStopWords.
Лемматизировать слова с помощью normalizeWords.
Стереть пунктуацию с помощью erasePunctuation.
Удаление слов, содержащих не более 2 символов removeShortWords.
Удаление слов с 15 или более символами с помощью removeLongWords.
Используйте примерную функцию предварительной обработки. preprocessText для подготовки текстовых данных.
newText = "The sorting machine is making lots of loud noises.";
newDocuments = preprocessText(newText)newDocuments = tokenizedDocument: 6 tokens: sorting machine make lot loud noise
Сравните предварительно обработанные данные с необработанными.
rawDocuments = tokenizedDocument(textData); rawBag = bagOfWords(rawDocuments)
rawBag =
bagOfWords with properties:
Counts: [480×555 double]
Vocabulary: [1×555 string]
NumWords: 555
NumDocuments: 480
Рассчитайте сокращение данных.
numWordsCleaned = cleanedBag.NumWords; numWordsRaw = rawBag.NumWords; reduction = 1 - numWordsCleaned/numWordsRaw
reduction = 0.7063
Сравните необработанные и очищенные данные, визуализируя две модели пакетов слов с помощью облаков слов.
figure subplot(1,2,1) wordcloud(rawBag); title("Raw Data") subplot(1,2,2) wordcloud(cleanedBag); title("Cleaned Data")

Функция preprocessText, выполняет следующие шаги в порядке:
Маркировка текста с помощью tokenizedDocument.
Удалите список стоп-слов (например, «and», «of» и «the»), используя removeStopWords.
Лемматизировать слова с помощью normalizeWords.
Стереть пунктуацию с помощью erasePunctuation.
Удаление слов, содержащих не более 2 символов removeShortWords.
Удаление слов с 15 или более символами с помощью removeLongWords.
function documents = preprocessText(textData) % Tokenize the text. documents = tokenizedDocument(textData); % Remove a list of stop words then lemmatize the words. To improve % lemmatization, first use addPartOfSpeechDetails. documents = addPartOfSpeechDetails(documents); documents = removeStopWords(documents); documents = normalizeWords(documents,'Style','lemma'); % Erase punctuation. documents = erasePunctuation(documents); % Remove words with 2 or fewer characters, and words with 15 or more % characters. documents = removeShortWords(documents,2); documents = removeLongWords(documents,15); end
addPartOfSpeechDetails | bagOfWords | erasePunctuation | normalizeWords | removeEmptyDocuments | removeInfrequentWords | removeLongWords | removeShortWords | removeStopWords | tokenizedDocument | wordcloud