main content

extract text data from files -凯发k8网页登录

this example shows how to extract the text data from text, html, microsoft® word, pdf, csv, and microsoft excel® files and import it into matlab® for analysis.

usually, the easiest way to import text data into matlab is to use the extractfiletext function. this function extracts the text data from text, pdf, html, and microsoft word files. to import text from csv and microsoft excel files, use readtable. to extract text from html code, use extracthtmltext. to read data from pdf forms, use readpdfformdata.

text file

extract the text from sonnets.txt using extractfiletext. the file sonnets.txt contains shakespeare's sonnets in plain text.

filename = "sonnets.txt";
str = extractfiletext(filename);

view the first sonnet by extracting the text between the two titles "i" and "ii".

start = " i"   newline;
fin = " ii";
sonnet1 = extractbetween(str,start,fin)
sonnet1 = 
    "
       from fairest creatures we desire increase,
       that thereby beauty's rose might never die,
       but as the riper should by time decease,
       his tender heir might bear his memory:
       but thou, contracted to thine own bright eyes,
       feed'st thy light's flame with self-substantial fuel,
       making a famine where abundance lies,
       thy self thy foe, to thy sweet self too cruel:
       thou that art now the world's fresh ornament,
       and only herald to the gaudy spring,
       within thine own bud buriest thy content,
       and tender churl mak'st waste in niggarding:
         pity the world, or else this glutton be,
         to eat the world's due, by the grave and thee.
     
      "

for text files containing multiple documents seperated by newline characters, use the readlines function.

filename = "multilinesonnets.txt";
str = readlines(filename)
str = 3×1 string
    "from fairest creatures we desire increase, that thereby beauty's rose might never die, but as the riper should by time decease, his tender heir might bear his memory: but thou, contracted to thine own bright eyes, feed'st thy light's flame with self-substantial fuel, making a famine where abundance lies, thy self thy foe, to thy sweet self too cruel: thou that art now the world's fresh ornament, and only herald to the gaudy spring, within thine own bud buriest thy content, and tender churl mak'st waste in niggarding: pity the world, or else this glutton be, to eat the world's due, by the grave and thee."
    "when forty winters shall besiege thy brow, and dig deep trenches in thy beauty's field, thy youth's proud livery so gazed on now, will be a tatter'd weed of small worth held: then being asked, where all thy beauty lies, where all the treasure of thy lusty days; to say, within thine own deep sunken eyes, were an all-eating shame, and thriftless praise. how much more praise deserv'd thy beauty's use, if thou couldst answer 'this fair child of mine shall sum my count, and make my old excuse,' proving his beauty by succession thine! this were to be new made when thou art old, and see thy blood warm when thou feel'st it cold."
    "look in thy glass and tell the face thou viewest now is the time that face should form another; whose fresh repair if now thou not renewest, thou dost beguile the world, unbless some mother. for where is she so fair whose unear'd womb disdains the tillage of thy husbandry? or who is he so fond will be the tomb, of his self-love to stop posterity? thou art thy mother's glass and she in thee calls back the lovely april of her prime; so thou through windows of thine age shalt see, despite of wrinkles this thy golden time. but if thou live, remember'd not to be, die single and thine image dies with thee."

microsoft word document

extract the text from sonnets.docx using extractfiletext. the file examplesonnets.docx contains shakespeare's sonnets in a microsoft word document.

filename = "examplesonnets.docx";
str = extractfiletext(filename);

view the second sonnet by extracting the text between the two titles "ii" and "iii".

start = " ii"   newline;
fin = " iii";
sonnet2 = extractbetween(str,start,fin)
sonnet2 = 
    "
       when forty winters shall besiege thy brow,
     
       and dig deep trenches in thy beauty's field,
     
       thy youth's proud livery so gazed on now,
     
       will be a tatter'd weed of small worth held:
     
       then being asked, where all thy beauty lies,
     
       where all the treasure of thy lusty days;
     
       to say, within thine own deep sunken eyes,
     
       were an all-eating shame, and thriftless praise.
     
       how much more praise deserv'd thy beauty's use,
     
       if thou couldst answer 'this fair child of mine
     
       shall sum my count, and make my old excuse,'
     
       proving his beauty by succession thine!
     
         this were to be new made when thou art old,
     
         and see thy blood warm when thou feel'st it cold.
     
      "

the example microsoft word document uses two newline characters between each line. to replace these characters with a single newline character, use the replace function.

sonnet2 = replace(sonnet2,[newline newline],newline)
sonnet2 = 
    "
       when forty winters shall besiege thy brow,
       and dig deep trenches in thy beauty's field,
       thy youth's proud livery so gazed on now,
       will be a tatter'd weed of small worth held:
       then being asked, where all thy beauty lies,
       where all the treasure of thy lusty days;
       to say, within thine own deep sunken eyes,
       were an all-eating shame, and thriftless praise.
       how much more praise deserv'd thy beauty's use,
       if thou couldst answer 'this fair child of mine
       shall sum my count, and make my old excuse,'
       proving his beauty by succession thine!
         this were to be new made when thou art old,
         and see thy blood warm when thou feel'st it cold.
      "

pdf files

extract text from pdf documents and data from pdf forms.

pdf document

extract the text from sonnets.pdf using extractfiletext. the file examplesonnets.pdf contains shakespeare's sonnets in a pdf.

filename = "examplesonnets.pdf";
str = extractfiletext(filename);

view the third sonnet by extracting the text between the two titles "iii" and "iv". this pdf has a space before each newline character.

start = " iii "   newline;
fin = "iv";
sonnet3 = extractbetween(str,start,fin)
sonnet3 = 
    " 
       look in thy glass and tell the face thou viewest 
       now is the time that face should form another; 
       whose fresh repair if now thou not renewest, 
       thou dost beguile the world, unbless some mother. 
       for where is she so fair whose unear'd womb 
       disdains the tillage of thy husbandry? 
       or who is he so fond will be the tomb, 
       of his self-love to stop posterity? 
       thou art thy mother's glass and she in thee 
       calls back the lovely april of her prime; 
       so thou through windows of thine age shalt see, 
       despite of wrinkles this thy golden time. 
         but if thou live, remember'd not to be, 
         die single and thine image dies with thee. 
     
     
      
       "

pdf form

to read text data from pdf forms, use readpdfformdata. the function returns a struct containing the data from the pdf form fields.

filename = "weatherreportform1.pdf";
data = readpdfformdata(filename)
data = struct with fields:
         event_type: "thunderstorm wind"
    event_narrative: "large tree down between plantersville and nettleton."

html

extract text from html files, html code, and the web.

html file

to extract text data from a saved html file, use extractfiletext.

filename = "examplesonnets.html";
str = extractfiletext(filename);

view the forth sonnet by extracting the text between the two titles "iv" and "v".

start = newline   "iv"   newline;
fin = newline   "v"   newline;
sonnet4 = extractbetween(str,start,fin)
sonnet4 = 
    "
     unthrifty loveliness, why dost thou spend
     upon thy self thy beauty's legacy?
     nature's bequest gives nothing, but doth lend,
     and being frank she lends to those are free:
     then, beauteous niggard, why dost thou abuse
     the bounteous largess given thee to give?
     profitless usurer, why dost thou use
     so great a sum of sums, yet canst not live?
     for having traffic with thy self alone,
     thou of thy self thy sweet self dost deceive:
     then how when nature calls thee to be gone,
     what acceptable audit canst thou leave?
     thy unused beauty must be tombed with thee,
     which, used, lives th' executor to be.
     "

html code

to extract text data from a string containing html code, use extracthtmltext.

code = "

by william shakespeare

"
; str = extracthtmltext(code)
str = 
    "the sonnets
     
     by william shakespeare"

from the web

to extract text data from a web page, first read the html code using webread, and then use extracthtmltext.

url = "https://www.mathworks.com/help/textanalytics";
code = webread(url);
str = extracthtmltext(code)
str = 
    'text analytics toolbox
     
     analyze and model text data 
     
     release notes
     
     pdf documentation
     
     release notes
     
     pdf documentation
     
     text analytics toolbox™ provides algorithms and visualizations for preprocessing, analyzing, and modeling text data. models created with the toolbox can be used in applications such as sentiment analysis, predictive maintenance, and topic modeling.
     
     text analytics toolbox includes tools for processing raw text from sources such as equipment logs, news feeds, surveys, operator reports, and social media. you can extract text from popular file formats, preprocess raw text, extract individual words, convert text into numerical representations, and build statistical models.
     
     using machine learning techniques such as lsa, lda, and word embeddings, you can find clusters and create features from high-dimensional text datasets. features created with text analytics toolbox can be combined with features from other data sources to build machine learning models that take advantage of textual, numeric, and other types of data.
     
     get started
     
     learn the basics of text analytics toolbox
     
     text data preparation
     
     import text data into matlab® and preprocess it for analysis
     
     modeling and prediction
     
     develop predictive models using topic models and word embeddings
     
     display and presentation
     
     visualize text data and models using word clouds and text scatter plots
     
     language support
     
     information on language support in text analytics toolbox'

parse html code

to find particular elements of html code, parse the code using htmltree and use findelement. parse the html code and find all the hyperlinks. the hyperlinks are nodes with element name "a".

tree = htmltree(code);
selector = "a";
subtrees = findelement(tree,selector);

view the first 10 subtrees and extract the text using extracthtmltext.

subtrees(1:10)
ans = 
  10×1 htmltree:
    
    
    
    
    
    
    
    
    
    
str = extracthtmltext(subtrees);

view the extracted text of the first 10 hyperlinks.

str(1:10)
ans = 10×1 string
    "skip to content"
    ""
    "products"
    "solutions"
    "academia"
    "support"
    "community"
    "events"
    "get matlab"
    ""

to get the link targets, use getattributes and specify the attribute "href" (hyperlink reference). get the link targets of the first 10 subtrees.

attr = "href";
str = getattribute(subtrees(1:10),attr)
str = 10×1 string
    "#skip_link_anchor"
    "https://www.mathworks.com?s_tid=gn_logo"
    "https://www.mathworks.com/products.html?s_tid=gn_ps"
    "https://www.mathworks.com/solutions.html?s_tid=gn_sol"
    "https://www.mathworks.com/academia.html?s_tid=gn_acad"
    "https://www.mathworks.com/support.html?s_tid=gn_supp"
    "https://www.mathworks.com/matlabcentral/?s_tid=gn_mlc"
    "https://www.mathworks.com/company/events.html?s_tid=gn_ev"
    "https://www.mathworks.com/products/get-matlab.html?s_tid=gn_getml"
    "https://www.mathworks.com?s_tid=gn_logo"

csv and microsoft excel files

to extract text data from csv and microsoft excel files, use readtable and extract the text data from the table that it returns.

extract the table data from factoryreposts.csv using the readtable function and view the first few rows of the table.

t = readtable('factoryreports.csv','texttype','string');
head(t)
                                 description                                       category          urgency          resolution         cost 
    _____________________________________________________________________    ____________________    ________    ____________________    _____
    "items are occasionally getting stuck in the scanner spools."            "mechanical failure"    "medium"    "readjust machine"         45
    "loud rattling and banging sounds are coming from assembler pistons."    "mechanical failure"    "medium"    "readjust machine"         35
    "there are cuts to the power when starting the plant."                   "electronic failure"    "high"      "full replacement"      16200
    "fried capacitors in the assembler."                                     "electronic failure"    "high"      "replace components"      352
    "mixer tripped the fuses."                                               "electronic failure"    "low"       "add to watch list"        55
    "burst pipe in the constructing agent is spraying coolant."              "leak"                  "high"      "replace components"      371
    "a fuse is blown in the mixer."                                          "electronic failure"    "low"       "replace components"      441
    "things continue to tumble off of the belt."                             "mechanical failure"    "low"       "readjust machine"         38

extract the text data from the event_narrative column and view the first few strings.

str = t.description;
str(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."

extract text from multiple files

if your text data is contained in multiple files in a folder, then you can import the text data into matlab using a file datastore.

create a file datastore for the example sonnet text files. the example files are named "examplesonnetn.txt", where n is the number of the sonnet. specify the file name using the wildcard "*" to find all file names of this structure. to specify the read function to be extractfiletext, input this function to filedatastore using a function handle.

location = "examplesonnet*.txt";
fds = filedatastore(location,'readfcn',@extractfiletext);

loop over the files in the datastore and read each text file.

str = [];
while hasdata(fds)
    textdata = read(fds);
    str = [str; textdata];
end

view the extracted text.

str
str = 4×1 string
    "  from fairest creatures we desire increase,↵  that thereby beauty's rose might never die,↵  but as the riper should by time decease,↵  his tender heir might bear his memory:↵  but thou, contracted to thine own bright eyes,↵  feed'st thy light's flame with self-substantial fuel,↵  making a famine where abundance lies,↵  thy self thy foe, to thy sweet self too cruel:↵  thou that art now the world's fresh ornament,↵  and only herald to the gaudy spring,↵  within thine own bud buriest thy content,↵  and tender churl mak'st waste in niggarding:↵    pity the world, or else this glutton be,↵    to eat the world's due, by the grave and thee."
    "  when forty winters shall besiege thy brow,↵  and dig deep trenches in thy beauty's field,↵  thy youth's proud livery so gazed on now,↵  will be a tatter'd weed of small worth held:↵  then being asked, where all thy beauty lies,↵  where all the treasure of thy lusty days;↵  to say, within thine own deep sunken eyes,↵  were an all-eating shame, and thriftless praise.↵  how much more praise deserv'd thy beauty's use,↵  if thou couldst answer 'this fair child of mine↵  shall sum my count, and make my old excuse,'↵  proving his beauty by succession thine!↵    this were to be new made when thou art old,↵    and see thy blood warm when thou feel'st it cold."
    "  look in thy glass and tell the face thou viewest↵  now is the time that face should form another;↵  whose fresh repair if now thou not renewest,↵  thou dost beguile the world, unbless some mother.↵  for where is she so fair whose unear'd womb↵  disdains the tillage of thy husbandry?↵  or who is he so fond will be the tomb,↵  of his self-love to stop posterity?↵  thou art thy mother's glass and she in thee↵  calls back the lovely april of her prime;↵  so thou through windows of thine age shalt see,↵  despite of wrinkles this thy golden time.↵    but if thou live, remember'd not to be,↵    die single and thine image dies with thee."
    "  unthrifty loveliness, why dost thou spend↵  upon thy self thy beauty's legacy?↵  nature's bequest gives nothing, but doth lend,↵  and being frank she lends to those are free:↵  then, beauteous niggard, why dost thou abuse↵  the bounteous largess given thee to give?↵  profitless usurer, why dost thou use↵  so great a sum of sums, yet canst not live?↵  for having traffic with thy self alone,↵  thou of thy self thy sweet self dost deceive:↵  then how when nature calls thee to be gone,↵  what acceptable audit canst thou leave?↵    thy unused beauty must be tombed with thee,↵    which, used, lives th' executor to be."

see also

| | | |

related topics

网站地图