У меня есть набор документов, содержащих предварительно обработанные тексты с html-страниц. Мне уже дали. Я хочу извлечь из него только слова. Я не хочу, чтобы какие-либо цифры или общие слова или какие-либо отдельные буквы были извлечены. Первая проблема, с которой я столкнулся, - это.Извлечь только слова из массива ячеек в matlab
Предположим, что у меня есть массив ячеек:
{'!' '!!' '!!!!)' '!!!!thanks' '!!dogsbreath' '!)' '!--[endif]--' '!--[if'}
Я хочу сделать массив ячеек, имеющий только слова - как это.
{'!!!!thanks' '!!dogsbreath' '!--[endif]--' '!--[if'}
А затем преобразовать это в этой ячейке массив
{'thanks' 'dogsbreath' 'endif' 'if'}
Есть ли способ сделать это?
Обновлено Требование: Благодаря все ваши ответы. Однако я столкнулся с проблемой! Позвольте мне проиллюстрировать это (Пожалуйста, обратите внимание, что значения ячеек извлекаются текст из HTML-документов и, следовательно, может содержать не являющееся значение ASCII) -
{'!/bin/bash' '![endif]' '!take-a-long' '!–photo'}
Это дает мне ответ
{'bin' 'bash' 'endif' 'take' 'a' 'long' 'â' 'photo' }
Моими вопросы:
- Почему bin/bash и take-a-long разделены на три ячейки? Это не проблема для меня, но почему? Можно ли этого избежать. Я имею в виду, что все слова, исходящие из одной ячейки, объединяются в одну.
- Обратите внимание, что в
'!–photo'
существует символ не-asciiâ
, который в данном случае означаетa
. Можно ли включить такой шаг, чтобы это преобразование было автоматическим? - Я заметил, что текст
"it? __________ About the Author:"
дает мне"__________"
как слово. Почему это так? - Также текст
"2. areoplane 3. cactus 4. a_rinny_boo... 5. trumpet 6. window 7. curtain ... 173. gypsy_wagon..."
возвращает слово'areoplane' 'cactus' 'a_rinny_boo' 'trumpet' 'window' 'curtain' 'gypsy_wagon'
. Я хочу, чтобы слова'a_rinny_boo'
и''gypsy_wagon
были'a' 'rinny' 'boo' 'gypsy' 'wagon'
. Это можно сделать?
Update 1 После всех предложений, которые я записал функцию, которая делает большинство вещей, кроме двух вышеупомянутых вновь задаваемых вопросов.
function [Text_Data] = raw_txt_gn(filename)
% This function will convert the text documnets into raw text
% It will remove all commas empty cells and other special characters
% It will also convert all the words of the text documents into lowercase
T = textread(filename, '%s');
% find all the important indices
ind1=find(ismember(T,':WebpageTitle:'));
T1 = T(ind1+1:end,1);
% Remove things which are not basically words
not_words = {'##','-',':ImageSurroundingText:',':WebpageDescription:',':WebpageKeywords:',' '};
T2 = []; count = 1;
for j=1:length(T1)
x = T1{j};
ind=find(ismember(not_words,x), 1);
if isempty(ind)
B = regexp(x, '\w*', 'match');
B(cellfun('isempty', B)) = []; % Clean out empty cells
B = [B{:}]; % Flatten cell array
% convert the string into lowecase
% so that while generating the features the case sensitivity is
% handled well
x = lower(B);
T2{count,1} = x;
count = count+1;
end
end
T2 = T2(~cellfun('isempty',T2));
% Getting the common words in the english language
% found from Wikipedia
not_words2 = {'the','be','to','of','and','a','in','that','have','i'};
not_words2 = [not_words2, 'it' 'for' 'not' 'on' 'with' 'he' 'as' 'you' 'do' 'at'];
not_words2 = [not_words2, 'this' 'but' 'his' 'by' 'from' 'they' 'we' 'say' 'her' 'she'];
not_words2 = [not_words2, 'or' 'an' 'will' 'my' 'one' 'all' 'would' 'there' 'their' 'what'];
not_words2 = [not_words2, 'so' 'up' 'out' 'if' 'about' 'who' 'get' 'which' 'go' 'me'];
not_words2 = [not_words2, 'when' 'make' 'can' 'like' 'time' 'no' 'just' 'him' 'know' 'take'];
not_words2 = [not_words2, 'people' 'into' 'year' 'your' 'good' 'some' 'could' 'them' 'see' 'other'];
not_words2 = [not_words2, 'than' 'then' 'now' 'look' 'only' 'come' 'its' 'over' 'think' 'also'];
not_words2 = [not_words2, 'back' 'after' 'use' 'two' 'how' 'our' 'work' 'first' 'well' 'way'];
not_words2 = [not_words2, 'even' 'new' 'want' 'because' 'any' 'these' 'give' 'day' 'most' 'us'];
for j=1:length(T2)
x = T2{j};
% if a particular cell contains only numbers then make it empty
if sum(isstrprop(x, 'digit'))~=0
T2{j} = [];
end
% also remove single character cells
if length(x)==1
T2{j} = [];
end
% also remove the most common words from the dictionary
% the common words are taken from the english dicitonary (source
% wikipedia)
ind=find(ismember(not_words2,x), 1);
if isempty(ind)==0
T2{j} = [];
end
end
Text_Data = T2(~cellfun('isempty',T2));
Update 2 Я нашел этот код в here, который говорит мне, как проверить, не-ASCII символов. Включение этого фрагмента кода в Matlab, как
% remove the non-ascii characters
if all(x < 128)
else
T2{j} = [];
end
и затем удаляя пустые ячейки, кажется, мое второе требование выполняется, хотя текст, содержащий часть не-ASCII символов полностью исчезает.
Могут ли мои окончательные требования быть заполнены? Большинство из них относится к персонажу '_'
и '-'
.
милый я только что узнал об этой функции спасибо! –
Аккуратная функция :) Спасибо, что поделились! – rayryeng
Можете ли вы заглянуть в мое обновленное требование? – roni