Docsity

Speech and Language Processing, Dispense di Linguistica

Toggle sidebar
bg1
Speech and Language Processing
An Introduction to Natural Language Processing,
Computational Linguistics, and Speech Recognition
Third Edition draft
Daniel Jurafsky
Stanford University
James H. Martin
University of Colorado at Boulder
Copyright c
2018
Draft of September 23, 2018. Comments and typos welcome!
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Anteprima parziale del testo

Scarica Speech and Language Processing e più Dispense in PDF di Linguistica solo su Docsity!

Speech and Language Processing

An Introduction to Natural Language Processing,

Computational Linguistics, and Speech Recognition

Third Edition draft

Daniel Jurafsky

Stanford University

James H. Martin

University of Colorado at Boulder

Copyright ©c 2018

Draft of September 23, 2018. Comments and typos welcome!

Summary of Contents

  • 1 Introduction.
  • 2 Regular Expressions, Text Normalization, Edit Distance
  • 3 N-gram Language Models
  • 4 Naive Bayes and Sentiment Classification
  • 5 Logistic Regression
  • 6 Vector Semantics
  • 7 Neural Networks and Neural Language Models
  • 8 Part-of-Speech Tagging
  • 9 Sequence Processing with Recurrent Networks
  • 10 Formal Grammars of English
  • 11 Syntactic Parsing
  • 12 Statistical Parsing
  • 13 Dependency Parsing
  • 14 The Representation of Sentence Meaning
  • 15 Computational Semantics
  • 16 Semantic Parsing
  • 17 Information Extraction
  • 18 Semantic Role Labeling
  • 19 Lexicons for Sentiment, Affect, and Connotation
  • 20 Coreference Resolution and Entity Linking
  • 21 Discourse Coherence.
  • 22 Machine Translation
  • 23 Question Answering
  • 24 Dialog Systems and Chatbots.
  • 25 Advanced Dialog Systems
  • 26 Speech Recognition and Synthesis
  • Appendix
    • A Hidden Markov Models
    • B Spelling Correction and the Noisy Channel
    • C WordNet: Word Relations, Senses, and Disambiguation
    • Bibliography
    • Author Index
    • Subject Index
  • 1 Introduction Contents
  • 2 Regular Expressions, Text Normalization, Edit Distance
    • 2.1 Regular Expressions
    • 2.2 Words
    • 2.3 Corpora
    • 2.4 Text Normalization
    • 2.5 Minimum Edit Distance
    • 2.6 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 3 N-gram Language Models
    • 3.1 N-Grams
    • 3.2 Evaluating Language Models
    • 3.3 Generalization and Zeros
    • 3.4 Smoothing
    • 3.5 Kneser-Ney Smoothing
    • 3.6 The Web and Stupid Backoff
    • 3.7 Advanced: Perplexity’s Relation to Entropy
    • 3.8 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 4 Naive Bayes and Sentiment Classification
    • 4.1 Naive Bayes Classifiers
    • 4.2 Training the Naive Bayes Classifier
    • 4.3 Worked example
    • 4.4 Optimizing for Sentiment Analysis
    • 4.5 Naive Bayes for other text classification tasks
    • 4.6 Naive Bayes as a Language Model
    • 4.7 Evaluation: Precision, Recall, F-measure
    • 4.8 Test sets and Cross-validation
    • 4.9 Statistical Significance Testing
    • 4.10 Advanced: Feature Selection
    • 4.11 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 5 Logistic Regression
    • 5.1 Classification: the sigmoid
    • 5.2 Learning in Logistic Regression
    • 5.3 The cross-entropy loss function
    • 5.4 Gradient Descent
    • 5.5 Regularization
    • 5.6 Multinomial logistic regression
    • 5.7 Interpreting models
    • 5.8 Advanced: Deriving the Gradient Equation
    • 5.9 Summary
    • Bibliographical and Historical Notes 4 CONTENTS
    • Exercises
  • 6 Vector Semantics
    • 6.1 Lexical Semantics
    • 6.2 Vector Semantics
    • 6.3 Words and Vectors
    • 6.4 Cosine for measuring similarity
    • 6.5 TF-IDF: Weighing terms in the vector
    • 6.6 Applications of the tf-idf vector model
    • 6.7 Optional: Pointwise Mutual Information (PMI)
    • 6.8 Word2vec
    • 6.9 Visualizing Embeddings
    • 6.10 Semantic properties of embeddings
    • 6.11 Bias and Embeddings
    • 6.12 Evaluating Vector Models
    • 6.13 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 7 Neural Networks and Neural Language Models
    • 7.1 Units
    • 7.2 The XOR problem
    • 7.3 Feed-Forward Neural Networks
    • 7.4 Training Neural Nets
    • 7.5 Neural Language Models
    • 7.6 Summary
    • Bibliographical and Historical Notes
  • 8 Part-of-Speech Tagging
    • 8.1 (Mostly) English Word Classes
    • 8.2 The Penn Treebank Part-of-Speech Tagset
    • 8.3 Part-of-Speech Tagging
    • 8.4 HMM Part-of-Speech Tagging
    • 8.5 Maximum Entropy Markov Models
    • 8.6 Bidirectionality
    • 8.7 Part-of-Speech Tagging for Other Languages
    • 8.8 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 9 Sequence Processing with Recurrent Networks
    • 9.1 Simple Recurrent Networks
    • 9.2 Applications of RNNs
    • 9.3 Deep Networks: Stacked and Bidirectional RNNs
    • 9.4 Managing Context in RNNs: LSTMs and GRUs
    • 9.5 Words, Characters and Byte-Pairs
    • 9.6 Summary
  • 10 Formal Grammars of English
    • 10.1 Constituency
    • 10.2 Context-Free Grammars
      • CONTENTS
    • 10.3 Some Grammar Rules for English
    • 10.4 Treebanks
    • 10.5 Grammar Equivalence and Normal Form
    • 10.6 Lexicalized Grammars
    • 10.7 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 11 Syntactic Parsing
    • 11.1 Ambiguity
    • 11.2 CKY Parsing: A Dynamic Programming Approach
    • 11.3 Partial Parsing
    • 11.4 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 12 Statistical Parsing
    • 12.1 Probabilistic Context-Free Grammars
    • 12.2 Probabilistic CKY Parsing of PCFGs
    • 12.3 Ways to Learn PCFG Rule Probabilities
    • 12.4 Problems with PCFGs
    • 12.5 Improving PCFGs by Splitting Non-Terminals
    • 12.6 Probabilistic Lexicalized CFGs
    • 12.7 Probabilistic CCG Parsing
    • 12.8 Evaluating Parsers
    • 12.9 Human Parsing
    • 12.10 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 13 Dependency Parsing
    • 13.1 Dependency Relations
    • 13.2 Dependency Formalisms
    • 13.3 Dependency Treebanks
    • 13.4 Transition-Based Dependency Parsing
    • 13.5 Graph-Based Dependency Parsing
    • 13.6 Evaluation
    • 13.7 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 14 The Representation of Sentence Meaning
    • 14.1 Computational Desiderata for Representations
    • 14.2 Model-Theoretic Semantics
    • 14.3 First-Order Logic
    • 14.4 Event and State Representations
    • 14.5 Description Logics
    • 14.6 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 15 Computational Semantics
  • 16 Semantic Parsing 6 CONTENTS
  • 17 Information Extraction
    • 17.1 Named Entity Recognition
    • 17.2 Relation Extraction
    • 17.3 Extracting Times
    • 17.4 Extracting Events and their Times
    • 17.5 Template Filling
    • 17.6 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 18 Semantic Role Labeling
    • 18.1 Semantic Roles
    • 18.2 Diathesis Alternations
    • 18.3 Semantic Roles: Problems with Thematic Roles
    • 18.4 The Proposition Bank
    • 18.5 FrameNet
    • 18.6 Semantic Role Labeling
    • 18.7 Selectional Restrictions
    • 18.8 Primitive Decomposition of Predicates
    • 18.9 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 19 Lexicons for Sentiment, Affect, and Connotation
    • 19.1 Defining Emotion
    • 19.2 Available Sentiment and Affect Lexicons
    • 19.3 Creating affect lexicons by human labeling
    • 19.4 Semi-supervised induction of affect lexicons
    • 19.5 Supervised learning of word sentiment
    • 19.6 Using Lexicons for Sentiment Recognition
    • 19.7 Other tasks: Personality
    • 19.8 Affect Recognition
    • 19.9 Connotation Frames
    • 19.10 Summary
    • Bibliographical and Historical Notes
  • 20 Coreference Resolution and Entity Linking
  • 21 Discourse Coherence
  • 22 Machine Translation
  • 23 Question Answering
    • 23.1 IR-based Factoid Question Answering
    • 23.2 Knowledge-based Question Answering
    • 23.3 Using multiple information sources: IBM’s Watson
    • 23.4 Evaluation of Factoid Answers
    • Bibliographical and Historical Notes
    • Exercises
  • 24 Dialog Systems and Chatbots - CONTENTS
    • 24.1 Chatbots
    • 24.2 Frame Based Dialog Agents
    • 24.3 VoiceXML
    • 24.4 Evaluating Dialog Systems
    • 24.5 Dialog System Design
    • 24.6 Summary
    • Bibliographical and Historical Notes
    • Exercises
  • 25 Advanced Dialog Systems
    • 25.1 Dialog Acts
    • 25.2 Dialog State: Interpreting Dialog Acts
    • 25.3 Dialog Policy
    • 25.4 A simple policy based on local context
    • 25.5 Natural language generation in the dialog-state model
    • 25.6 Deep Reinforcement Learning for Dialog
    • 25.7 Summary
    • Bibliographical and Historical Notes
  • 26 Speech Recognition and Synthesis
  • Appendix
  • A Hidden Markov Models
    • A.1 Markov Chains
    • A.2 The Hidden Markov Model
    • A.3 Likelihood Computation: The Forward Algorithm
    • A.4 Decoding: The Viterbi Algorithm
    • A.5 HMM Training: The Forward-Backward Algorithm
    • A.6 Summary
    • Bibliographical and Historical Notes
  • B Spelling Correction and the Noisy Channel
    • B.1 The Noisy Channel Model
    • B.2 Real-word spelling errors
    • B.3 Noisy Channel Model: The State of the Art
    • Bibliographical and Historical Notes
    • Exercises
  • C WordNet: Word Relations, Senses, and Disambiguation
    • C.1 Word Senses
    • C.2 WordNet: A Database of Lexical Relations
    • C.3 Word Similarity: Thesaurus Methods
    • C.4 Word Sense Disambiguation: Overview
    • C.5 Supervised Word Sense Disambiguation
    • C.6 WSD: Dictionary and Thesaurus Methods
    • C.7 Semi-Supervised WSD: Bootstrapping
    • C.8 Unsupervised Word Sense Induction
    • C.9 Summary
    • Bibliographical and Historical Notes
    • Exercises
8 CONTENTS

Bibliography 517

Author Index 543

Subject Index 551

10 CHAPTER 2 • REGULAR EXPRESSIONS, TEXT NORMALIZATION, EDIT DISTANCE
CHAPTER

Regular Expressions, Text

Normalization, Edit Distance

User: You are like my father in some ways. ELIZA: WHAT RESEMBLANCE DO YOU SEE User: You are not very aggressive but I think you don’t want me to notice that. ELIZA: WHAT MAKES YOU THINK I AM NOT VERY AGGRESSIVE User: You don’t argue with me. ELIZA: WHY DO YOU THINK I DON’T ARGUE WITH YOU User: You are afraid of me. ELIZA: DOES IT PLEASE YOU TO BELIEVE I AM AFRAID OF YOU Weizenbaum (1966) ELIZA The dialogue above is from ELIZA, an early natural language processing sys- tem that could carry on a limited conversation with a user by imitating the responses of a Rogerian psychotherapist (Weizenbaum, 1966). ELIZA is a surprisingly simple program that uses pattern matching to recognize phrases like “You are X” and trans- late them into suitable outputs like “What makes you think I am X?”. This simple technique succeeds in this domain because ELIZA doesn’t actually need to know anything to mimic a Rogerian psychotherapist. As Weizenbaum notes, this is one of the few dialogue genres where listeners can act as if they know nothing of the world. Eliza’s mimicry of human conversation was remarkably successful: many people who interacted with ELIZA came to believe that it really understood them and their problems, many continued to believe in ELIZA’s abilities even after the program’s operation was explained to them (Weizenbaum, 1976), and even today chatbots such chatbots are a fun diversion. Of course modern conversational agents are much more than a diversion; they can answer questions, book flights, or find restaurants, functions for which they rely on a much more sophisticated understanding of the user’s intent, as we will see in Chapter 24. Nonetheless, the simple pattern-based methods that powered ELIZA and other chatbots play a crucial role in natural language processing. We’ll begin with the most important tool for describing text patterns: the regular expression. Regular expressions can be used to specify strings we might want to extract from a document, from transforming “You are X” in Eliza above, to defining strings like $ 199 or $24.99 for extracting tables of prices from a document. normalizationtext We’ll then turn to a set of tasks collectively called^ text normalization, in which regular expressions play an important part. Normalizing text means converting it to a more convenient, standard form. For example, most of what we are going to do with language relies on first separating out or tokenizing words from running tokenization text, the task of tokenization. English words are often separated from each other by whitespace, but whitespace is not always sufficient. New York and rock ’n’ roll are sometimes treated as large words despite the fact that they contain spaces, while sometimes we’ll need to separate I’m into the two words I and am. For processing tweets or texts we’ll need to tokenize emoticons like :) or hashtags like #nlproc. Some languages, like Chinese, don’t have spaces between words, so word tokeniza- tion becomes more difficult.

2.1 • REGULAR EXPRESSIONS 11

lemmatization Another part of text normalization is lemmatization, the task of determining that two words have the same root, despite their surface differences. For example, the words sang, sung, and sings are forms of the verb sing. The word sing is the common lemma of these words, and a lemmatizer maps from all of these to sing. Lemmatization is essential for processing morphologically complex languages like stemming Arabic. Stemming refers to a simpler version of lemmatization in which we mainly just strip suffixes from the end of the word. Text normalization also includes sen- segmentationsentence tence segmentation: breaking up a text into individual sentences, using cues like periods or exclamation points. Finally, we’ll need to compare words and other strings. We’ll introduce a metric called edit distance that measures how similar two strings are based on the number of edits (insertions, deletions, substitutions) it takes to change one string into the other. Edit distance is an algorithm with applications throughout language process- ing, from spelling correction to speech recognition to coreference resolution.

2.1 Regular Expressions

SIR ANDREW: Her C’s, her U’s and her T’s: why that? Shakespeare, Twelfth Night One of the unsung successes in standardization in computer science has been the expressionregular^ regular expression^ (RE), a language for specifying text search strings. This prac- tical language is used in every computer language, word processor, and text pro- cessing tools like the Unix tools grep or Emacs. Formally, a regular expression is an algebraic notation for characterizing a set of strings. They are particularly use- corpus ful for searching in texts, when we have a pattern to search for and a corpus of texts to search through. A regular expression search function will search through the corpus, returning all texts that match the pattern. The corpus can be a single docu- ment or a collection. For example, the Unix command-line tool grep takes a regular expression and returns every line of the input document that matches the expression. A search can be designed to return every match on a line, if there are more than one, or just the first match. In the following examples we generally underline the exact part of the pattern that matches the regular expression and show only the first match. We’ll show regular expressions delimited by slashes but note that slashes are not part of the regular expressions. Regular expressions come in many variants. We’ll be describing extended regu- lar expressions; different regular expression parsers may only recognize subsets of these, or treat some expressions slightly differently. Using an online regular expres- sion tester is a handy way to test out your expressions and explore these variations.

2.1.1 Basic Regular Expression Patterns

The simplest kind of regular expression is a sequence of simple characters. To search for woodchuck, we type /woodchuck/. The expression /Buttercup/ matches any string containing the substring Buttercup; grep with that expression would return the line I’m called little Buttercup. The search string can consist of a single character (like /!/) or a sequence of characters (like /urgl/). Regular expressions are case sensitive; lower case /s/ is distinct from upper case /S/ (/s/ matches a lower case s but not an upper case S). This means that the pattern /woodchucks/ will not match the string Woodchucks. We can solve this

2.1 • REGULAR EXPRESSIONS 13

RE Match Example Patterns Matched /woodchucks?/ woodchuck or woodchucks “woodchuck” /colou?r/ color or colour “colour” Figure 2.5 The question mark? marks optionality of the previous expression.

We can think of the question mark as meaning “zero or one instances of the previous character”. That is, it’s a way of specifying how many of something that we want, something that is very important in regular expressions. For example, consider the language of certain sheep, which consists of strings that look like the following:

baa! baaa! baaaa! baaaaa!

...

This language consists of strings with a b, followed by at least two a’s, followed by an exclamation point. The set of operators that allows us to say things like “some Kleene * number of as” are based on the asterisk or , commonly called the Kleene * (gen- erally pronounced “cleany star”). The Kleene star means “zero or more occurrences of the immediately previous character or regular expression”. So /a/ means “any string of zero or more as”. This will match a or aaaaaa, but it will also match Off Minor since the string Off Minor has zero a’s. So the regular expression for matching one or more a is /aa/, meaning one a followed by zero or more as. More complex patterns can also be repeated. So /[ab]/ means “zero or more a’s or b’s” (not “zero or more right square braces”). This will match strings like aaaa or ababab or bbbb. For specifying multiple digits (useful for finding prices) we can extend /[0-9]/, the regular expression for a single digit. An integer (a string of digits) is thus /[0-9][0-9]/. (Why isn’t it just /[0-9]/?) Sometimes it’s annoying to have to write the regular expression for digits twice, so there is a shorter way to specify “at least one” of some character. This is the Kleene + Kleene +, which means “one or more occurrences of the immediately preceding character or regular expression”. Thus, the expression /[0-9]+/ is the normal way to specify “a sequence of digits”. There are thus two ways to specify the sheep language: /baaa*!/ or /baa+!/. One very important special character is the period (/./), a wildcard expression that matches any single character (except a carriage return), as shown in Fig. 2.6.

RE Match Example Matches /beg.n/ any character between beg and n begin, beg’n, begun Figure 2.6 The use of the period. to specify any character.

The wildcard is often used together with the Kleene star to mean “any string of characters”. For example, suppose we want to find any line in which a particular word, for example, aardvark, appears twice. We can specify this with the regular expression /aardvark.*aardvark/. Anchors Anchors are special characters that anchor regular expressions to particular places in a string. The most common anchors are the caret ˆ and the dollar sign $. The caret ˆ matches the start of a line. The pattern /ˆThe/ matches the word The only at the

14 CHAPTER 2 • REGULAR EXPRESSIONS, TEXT NORMALIZATION, EDIT DISTANCE

start of a line. Thus, the caret ˆ has three uses: to match the start of a line, to in- dicate a negation inside of square brackets, and just to mean a caret. (What are the contexts that allow grep or Python to know which function a given caret is supposed to have?) The dollar sign $ matches the end of a line. So the pattern $ is a useful pattern for matching a space at the end of a line, and /ˆThe dog.$/ matches a line that contains only the phrase The dog. (We have to use the backslash here since we want the. to mean “period” and not the wildcard.) There are also two other anchors: \b matches a word boundary, and \B matches a non-boundary. Thus, /\bthe\b/ matches the word the but not the word other. More technically, a “word” for the purposes of a regular expression is defined as any sequence of digits, underscores, or letters; this is based on the definition of “words” in programming languages. For example, /\b99\b/ will match the string 99 in There are 99 bottles of beer on the wall (because 99 follows a space) but not 99 in There are 299 bottles of beer on the wall (since 99 follows a number). But it will match 99 in $ 99 (since 99 follows a dollar sign ($), which is not a digit, underscore, or letter).

2.1.2 Disjunction, Grouping, and Precedence

Suppose we need to search for texts about pets; perhaps we are particularly interested in cats and dogs. In such a case, we might want to search for either the string cat or the string dog. Since we can’t use the square brackets to search for “cat or dog” (why disjunction can’t we say /[catdog]/?), we need a new operator, the disjunction operator, also called the pipe symbol |. The pattern /cat|dog/ matches either the string cat or the string dog. Sometimes we need to use this disjunction operator in the midst of a larger se- quence. For example, suppose I want to search for information about pet fish for my cousin David. How can I specify both guppy and guppies? We cannot simply say /guppy|ies/, because that would match only the strings guppy and ies. This Precedence is because sequences like guppy take precedence over the disjunction operator |. To make the disjunction operator apply only to a specific pattern, we need to use the parenthesis operators ( and ). Enclosing a pattern in parentheses makes it act like a single character for the purposes of neighboring operators like the pipe | and the Kleene. So the pattern /gupp(y|ies)/ would specify that we meant the disjunc- tion only to apply to the suffixes y and ies. The parenthesis operator ( is also useful when we are using counters like the Kleene. Unlike the | operator, the Kleene* operator applies by default only to a single character, not to a whole sequence. Suppose we want to match repeated instances of a string. Perhaps we have a line that has column labels of the form Column 1 Column 2 Column 3. The expression /Column [0-9]+ */ will not match any number of columns; instead, it will match a single column followed by any number of spaces! The star here applies only to the space that precedes it, not to the whole sequence. With the parentheses, we could write the expression /(Column [0-9]+ )/ to match the word Column, followed by a number and optional spaces, the whole pattern repeated any number of times. This idea that one operator may take precedence over another, requiring us to sometimes use parentheses to specify what we mean, is formalized by the operator precedenceoperator precedence hierarchy^ for regular expressions. The following table gives the order of RE operator precedence, from highest precedence to lowest precedence.

16 CHAPTER 2 • REGULAR EXPRESSIONS, TEXT NORMALIZATION, EDIT DISTANCE

errors comes up again and again in implementing speech and language processing systems. Reducing the overall error rate for an application thus involves two antag- onistic efforts:

  • Increasing precision (minimizing false positives)
  • Increasing recall (minimizing false negatives)
2.1.4 A More Complex Example

Let’s try out a more significant example of the power of REs. Suppose we want to build an application to help a user buy a computer on the Web. The user might want “any machine with at least 6 GHz and 500 GB of disk space for less than $1000”. To do this kind of retrieval, we first need to be able to look for expressions like 6 GHz or 500 GB or Mac or $999.99. In the rest of this section we’ll work out some simple regular expressions for this task. First, let’s complete our regular expression for prices. Here’s a regular expres- sion for a dollar sign followed by a string of digits:

/$[0-9]+/

Note that the $ character has a different function here than the end-of-line function we discussed earlier. Most regular expression parsers are smart enough to realize that $ here doesn’t mean end-of-line. (As a thought experiment, think about how regex parsers might figure out the function of $ from the context.) Now we just need to deal with fractions of dollars. We’ll add a decimal point and two digits afterwards:

/$[0-9]+.[0-9][0-9]/

This pattern only allows $199.99 but not $ 199. We need to make the cents optional and to make sure we’re at a word boundary:

/(ˆ|\W)$[0-9]+(.[0-9][0-9])?\b/

One last catch! This pattern allows prices like $199999.99 which would be far too expensive! We need to limit the dollar

/(ˆ|\W)$[0-9]{0,3}(.[0-9][0-9])?\b/

How about specifications for > 6GHz processor speed? Here’s a pattern for that:

/\b[6-9]+ *(GHz|[Gg]igahertz)\b/

Note that we use / */ to mean “zero or more spaces” since there might always be extra spaces lying around. For disk space, we’ll need to allow for optional frac- tions again (5.5 GB); note the use of? for making the final s optional:

/\b[0-9]+(.[0-9]+)? *(GB|[Gg]igabytes?)\b/

Modifying this regular expression so that it only matches more than 500 GB is left as an exercise for the reader.

2.1.5 More Operators

Figure 2.7 shows some aliases for common ranges, which can be used mainly to save typing. Besides the Kleene * and Kleene + we can also use explicit numbers as

2.1 • REGULAR EXPRESSIONS 17

counters, by enclosing them in curly brackets. The regular expression /{3}/ means “exactly 3 occurrences of the previous character or expression”. So /a.{24}z/ will match a followed by 24 dots followed by z (but not a followed by 23 or 25 dots followed by a z).

RE Expansion Match First Matches \d [0-9] any digit Party of 5 \D [ˆ0-9] any non-digit Blue moon \w [a-zA-Z0-9_] any alphanumeric/underscore Daiyu \W [ˆ\w] a non-alphanumeric !!!! \s [ \r\t\n\f] whitespace (space, tab) \S [ˆ\s] Non-whitespace in Concord Figure 2.7 Aliases for common sets of characters.

A range of numbers can also be specified. So /{n,m}/ specifies from n to m occurrences of the previous char or expression, and /{n,}/ means at least n occur- rences of the previous expression. REs for counting are summarized in Fig. 2.8.

RE Match

  • zero or more occurrences of the previous char or expression
  • one or more occurrences of the previous char or expression ? exactly zero or one occurrence of the previous char or expression {n} n occurrences of the previous char or expression {n,m} from n to m occurrences of the previous char or expression {n,} at least n occurrences of the previous char or expression {,m} up to m occurrences of the previous char or expression Figure 2.8 Regular expression operators for counting.

Finally, certain special characters are referred to by special notation based on the Newline backslash () (see Fig. 2.9). The most common of these are the newline character \n and the tab character \t. To refer to characters that are special themselves (like ., *, [, and ), precede them with a backslash, (i.e., /./, /*/, /[/, and /\/).

RE Match First Patterns Matched * an asterisk “” “KAPLAN” . a period “.” “Dr. Livingston, I presume” ? a question mark “Why don’t they come and lend a hand?” \n a newline \t a tab Figure 2.9 Some characters that need to be backslashed.

2.1.6 Regular Expression Substitution, Capture Groups, and ELIZA

substitution An important use of regular expressions is in substitutions. For example, the substi- tution operator s/regexp1/pattern/ used in Python and in Unix commands like vim or sed allows a string characterized by a regular expression to be replaced by another string: s/colour/color/ It is often useful to be able to refer to a particular subpart of the string matching the first pattern. For example, suppose we wanted to put angle brackets around all

2.2 • WORDS 19

s/.* I’M (depressed|sad) ./I AM SORRY TO HEAR YOU ARE \1/ s/. I AM (depressed|sad) ./WHY DO YOU THINK YOU ARE \1/ s/. all ./IN WHAT WAY/ s/. always .*/CAN YOU THINK OF A SPECIFIC EXAMPLE/

Since multiple substitutions can apply to a given input, substitutions are assigned a rank and applied in order. Creating patterns is the topic of Exercise 2.3, and we return to the details of the ELIZA architecture in Chapter 24.

2.1.7 Lookahead assertions

Finally, there will be times when we need to predict the future: look ahead in the text to see if some pattern matches, but not advance the match cursor, so that we can then deal with the pattern if it occurs. lookahead These lookahead assertions make use of the (? syntax that we saw in the previ- ous section for non-capture groups. The operator (?= pattern) is true if pattern zero-width occurs, but is zero-width, i.e. the match pointer doesn’t advance. The operator (?! pattern) only returns true if a pattern does not match, but again is zero-width and doesn’t advance the cursor. Negative lookahead is commonly used when we are parsing some complex pattern but want to rule out a special case. For example suppose we want to match, at the beginning of a line, any single word that doesn’t start with “Volcano”. We can use negative lookahead to do this: /ˆ(?!Volcano)[A-Za-z]+/

2.2 Words

Before we talk about processing words, we need to decide what counts as a word. corpus Let’s start by looking at one particular corpus (plural corpora), a computer-readable corpora (^) collection of text or speech. For example the Brown corpus is a million-word col- lection of samples from 500 written English texts from different genres (newspa- per, fiction, non-fiction, academic, etc.), assembled at Brown University in 1963– (Kuˇcera and Francis, 1967). How many words are in the following Brown sentence? He stepped out into the hall, was delighted to encounter a water brother. This sentence has 13 words if we don’t count punctuation marks as words, 15 if we count punctuation. Whether we treat period (“.”), comma (“,”), and so on as words depends on the task. Punctuation is critical for finding boundaries of things (commas, periods, colons) and for identifying some aspects of meaning (question marks, exclamation marks, quotation marks). For some tasks, like part-of-speech tagging or parsing or speech synthesis, we sometimes treat punctuation marks as if they were separate words. The Switchboard corpus of American English telephone conversations between strangers was collected in the early 1990s; it contains 2430 conversations averaging 6 minutes each, totaling 240 hours of speech and about 3 million words (Godfrey et al., 1992). Such corpora of spoken language don’t have punctuation but do intro- duce other complications with regard to defining words. Let’s look at one utterance utterance from Switchboard; an utterance is the spoken correlate of a sentence:

I do uh main- mainly business data processing

20 CHAPTER 2 • REGULAR EXPRESSIONS, TEXT NORMALIZATION, EDIT DISTANCE

disfluency This utterance has two kinds of disfluencies. The broken-off word main- is fragment called a fragment. Words like uh and um are called fillers or filled pauses. Should filled pause (^) we consider these to be words? Again, it depends on the application. If we are building a speech transcription system, we might want to eventually strip out the disfluencies. But we also sometimes keep disfluencies around. Disfluencies like uh or um are actually helpful in speech recognition in predicting the upcoming word, because they may signal that the speaker is restarting the clause or idea, and so for speech recognition they are treated as regular words. Because people use different disflu- encies they can also be a cue to speaker identification. In fact Clark and Fox Tree (2002) showed that uh and um have different meanings. What do you think they are? Are capitalized tokens like They and uncapitalized tokens like they the same word? These are lumped together in some tasks (speech recognition), while for part- of-speech or named-entity tagging, capitalization is a useful feature and is retained. How about inflected forms like cats versus cat? These two words have the same lemma lemma cat but are different wordforms. A lemma is a set of lexical forms having the same stem, the same major part-of-speech, and the same word sense. The word- wordform form is the full inflected or derived form of the word. For morphologically complex languages like Arabic, we often need to deal with lemmatization. For many tasks in English, however, wordforms are sufficient. How many words are there in English? To answer this question we need to word type distinguish two ways of talking about words. Types are the number of distinct words in a corpus; if the set of words in the vocabulary is V , the number of types is the word token vocabulary size |V |. Tokens are the total number N of running words. If we ignore punctuation, the following Brown sentence has 16 tokens and 14 types: They picnicked by the pool, then lay back on the grass and looked at the stars. When we speak about the number of words in the language, we are generally referring to word types.

Corpus Tokens = N Types = |V | Shakespeare 884 thousand 31 thousand Brown corpus 1 million 38 thousand Switchboard telephone conversations 2.4 million 20 thousand COCA 440 million 2 million Google N-grams 1 trillion 13 million Figure 2.10 Rough numbers of types and tokens for some English language corpora. The largest, the Google N-grams corpus, contains 13 million types, but this count only includes types appearing 40 or more times, so the true number would be much larger.

Fig. 2.10 shows the rough numbers of types and tokens computed from some popular English corpora. The larger the corpora we look at, the more word types we find, and in fact this relationship between the number of types |V | and number Herdan’s Law of tokens N is called Herdan’s Law (Herdan, 1960) or Heaps’ Law (Heaps, 1978) Heaps’ Law (^) after its discoverers (in linguistics and information retrieval respectively). It is shown in Eq. 2.1, where k and β are positive constants, and 0 < β < 1.

|V | = kNβ^ (2.1)

The value of β depends on the corpus size and the genre, but at least for the large corpora in Fig. 2.10, β ranges from .67 to .75. Roughly then we can say that