0% found this document useful (0 votes)
3 views52 pages

ComputerSysAndProgramming 8

Uploaded by

raniaalfiky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views52 pages

ComputerSysAndProgramming 8

Uploaded by

raniaalfiky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Cairo University

Faculty of Graduate Studies for Statistical Research


Department of Computer and Information Sciences

Computer Sys. And Programming


Lec. 8 outline: You’ll find all the information you need here on A
Sentence Generator, The Structure of a Sentence, Grammar Rules,
Dictionaries, Data Structures, Acessing a Value with a Key,
Replacing an Existing Value, The Doctor Program, Data Structures
for the Program, ….and ….
Tarek Aly
01126182476
http://41.32.221.109:8080/DrTarekAly.htm
E-mail: tarekmmmmt@{pg.cu.edu.eg; egyptpost.org; gmail.com; yahoo.com}
Contents
 A Sentence Generator
 Application: Generate Sentences
 The Structure of a Sentence
 Picking a Word at Random
 Grammar Rules
 Define a Function for Each Rule
 Dictionaries
 Data Structures
 Acessing a Value with a Key
 Alternative: Use the get Method
 Inserting a New Key/Value
 Replacing an Existing Value
 The Doctor Program
 Data Structures for the Program

10/2/2023 Computer Sys. And Programming


Application: Generate Sentences
 Given a vocabulary and grammar rules, one can
generate some random and perhaps rather silly
sentences

 Vocabulary - the set of words belonging to the


parts of speech (nouns, verbs, articles,
prepositions)

 Grammar - the set of rules for building phrases


in a sentence (noun phrase, verb phrase,
prepositional phrase)
The Structure of a Sentence
sentence

noun phrase verb phrase

A sentence is a noun phrase followed by a verb phrase


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun

A noun phrase is an article followed by a noun


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun

the Similar
girl to the behavior of strings so far

Pick actual words for those parts of speech at random


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

the Similar
girl to the behavior of strings so far
A verb phrase is a verb followed by a noun phrase and a
prepositional phrase
The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

the Similarthrew
girl to the behavior of strings so far

Pick a verb at random


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

article noun

the Similarthrew
girl to the behavior of strings so far

Expand a noun phrase again


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

article noun

the Similarthrew
girl to the behavior
the of
pie strings so far

Pick an article and a noun at random


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

article noun preposition noun phrase

the Similarthrew
girl to the behavior
the of
pie strings so far
A prepositional phrase is a preposition followed by a noun
phrase
The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

article noun preposition noun phrase

the Similarthrew
girl to the behavior
the of
pie stringsatso far

Pick a preposition at random


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

article noun preposition noun phrase

article noun

the Similarthrew
girl to the behavior
the of
pie stringsatso far

Expand another noun phrase


The Structure of a Sentence
sentence

noun phrase verb phrase

article noun verb noun phrase prepositional phrase

article noun preposition noun phrase

article noun

the Similarthrew
girl to the behavior
the of
pie stringsatso far a boy

More random words from the parts of speech


Representing the Vocabulary
nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair',
'fence', 'table', 'computer', 'cake', 'field’, 'pie']

verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped']

prepositions = ['with', 'to', 'from', 'on', 'below',


'above', 'beside', 'at']

articles = ['a', 'the']

Use a list of words for each part of speech (lexical category)


Picking a Word at Random
nouns = ['bat', 'boy', 'girl', 'dog', 'cat', 'chair',
'fence', 'table', 'computer', 'cake', 'field’, 'pie']

verbs = ['hit', 'threw', 'pushed', 'ate', 'dragged', 'jumped']

prepositions = ['with', 'to', 'from', 'on', 'below',


'above', 'beside', 'at']

articles = ['a', 'the']

import random

print(random.choice(verbs)) # Prints a randomly chosen verb

The random module includes functions to select numbers,


sequence elements, etc., at random
Grammar Rules
sentence = nounphrase verbphrase

nounphrase = article noun

verbphrase = verb nounphrase prepositionalphrase

preopositonalphrase = preposition nounphrase

A sentence is a noun phrase followed by a verb phrase

Etc., etc.
Define a Function for Each Rule
# sentence = nounphrase verbphrase
def sentence():
return nounphrase() + ' ' + verbphrase()

Each function builds and returns a string that is an instance


of the phrase

Separate phrases and words with a space


Define a Function for Each Rule
# sentence = nounphrase verbphrase
def sentence():
return nounphrase() + verbphrase()

# nounphrase = article noun


def nounphrase():
return random.choice(articles) + ' ' + random.choice(nouns)

When a part of speech is reached, select an instance at


random from the relevant list
Call sentence() to Try It Out
# sentence = nounphrase verbphrase
def sentence():
return nounphrase() + verbphrase()

# nounphrase = article noun


def nounphrase():
return random.choice(articles) + ' ' + random.choice(nouns)

for x in range(10): print(sentence()) # Display 10 sentences

You can also generate examples of the other phrases by


calling their functions
Dictionaries
Data Structures
 A data structure is a means of organizing
several data elements so they can be treated
as one thing

 A sequence is a data structure in which the


elements are accessible by position (first ..
last)

 A dictionary is a data structure in which the


elements are accessible by content
Examples of Dictionaries
 Dictionary
Elements may also be ordered
 Phone book alphabetically, but they need not be
 Thesaurus
 Encyclopedia
 Cookbook
 World Wide Web
Examples of Dictionaries
 Dictionary
An element is accessed by content
 Phone book
 Thesaurus This content can be
 Encyclopedia A word
A person’s name
 Cookbook A food type
 World Wide Web A text phrase or an image
Examples of Dictionaries
 Dictionary
An element is accessed by content
 Phone book
 Thesaurus This content can be
 Encyclopedia A word
A person’s name
 Cookbook A food type
 World Wide Web A text phrase or an image

Each content is called a key

Each associated element is called a


value
Characteristics of a Dictionary
 A dictionary is a set of keys associated with
values

 The keys are unique and need not be ordered


by position or alphabetically

 Values can be duplicated

 Keys and values can be of any data types


Examples of Keys and Values
Some hexadecimal (base16) A database of Ken’s info
digits and their values
'A' 10 'name' 'Ken'
'B' 11 'age' 67
'C' 12 'gender' 'M'
'D' 13 'occupation' 'teacher'
'E' 14 'hobbies' ['movies',
'F' 15 'gardening']
Dictionaries in Python
hexdigits = {'A':10, 'B':11, 'C':12,
'D':13, 'E':14, 'F':15}

database = {'name':'Ken', 'age':67,


'gender':'M', 'occupation':'teacher'}

an_empty_one = {}

Syntax:
{<key> : <value>, … , <key> : <value>}
Acessing a Value with a Key
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> database['name']
'Ken'

>>> database['age']
67

The subscript expects a key in the dictionary and returns


the associated value
<dictionary>[<key>]
Key Must be in the Dictionary
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> database['hair color']

Traceback (most recent call last):


File "<pyshell#6>", line 1, in -toplevel-
database['hair color']
KeyError: 'hair color'
Guard Access with an if
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> if 'hair color' in database:


database['hair color']

The in operator can be used to search any sequence or dictionary


Alternative: Use the get Method
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> database.get('hair color', None)


None

If the key (first argument) is in the dictionary, the value is returned

Otherwise, the default value (second argument) is returned


The for Loop Visits All Keys
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> for key in database:


print(key, database[key])
gender M
age 67
name Ken
occupation teacher
Inserting a New Key/Value
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> database['hair color'] = 'gray'

If the key is not already in the dictionary, Python creates one and
inserts it with the associated value
Inserting a New Key/Value
hexdigits = {'A':10, 'B':11, 'C':12,
'D':13, 'E':14, 'F':15}

>>> for i in range(10):


hexdigits[str(i)] = i

>>> hexdigits
{'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15,
'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4,
'7': 7, '6': 6, '9': 9, '8': 8}

Insert the remaining hexadecimal digits and their integer values


Replacing an Existing Value
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> database['age'] = database['age'] + 1

If the key is already in the dictionary, Python replaces the


associated value with the new one
Removing a key
>>> database = {'name':'Ken', 'age':67,
'gender':'M', 'occupation':'teacher'}

>>> database.pop('age', None)


67

The pop method removes the key and its associated value and
returns this value
Another Application:
Non-Directive Psychotherapy
Good morning, Ken, how can I help you today?

>

The therapist opens the session with a leading question, and waits
for the patient’s reply
Another Application:
Non-Directive Psychotherapy
Good morning, Ken, how can I help you today?

> My teacher hates me.

The therapist lets the patient provide most of the content


The patient replies with a statement
Another Application:
Non-Directive Psychotherapy
Good morning, Ken, how can I help you today?

> My teacher hates me.

Why do you say that your teacher hates you?

The therapist lets the patient provide most of the content


She responds by rephrasing the patient’s statement as a request for
more information
She includes the patient’s content by switching persons in the
replies (‘me’ becomes ‘you,’ ‘my’ becomes ‘your’, etc.)
Another Application:
Non-Directive Psychotherapy
Good morning, Ken, how can I help you today?

> My teacher hates me.

Why do you say that your teacher hates you?

> She always calls on the girls in the class.

The therapist lets the patient provide most of the content


She responds by rephrasing the patient’s statement as a request for more
information
She includes the patient’s content by switching persons in the replies (‘I’
becomes ‘you,’ ‘my’ becomes ‘your’, etc.)
Another Application:
Non-Directive Psychotherapy
Good morning, Ken, how can I help you today?

> My teacher hates me.

Why do you say that your teacher hates you?

> She always calls on the girls in the class.

Please tell me more.


>

Alternatively, the therapist tries to move the conversation forward


with a hedge.
The Doctor Program
1. The patient inputs a sentence

2. The doctor replies by either


a. Exploding the patient’s sentence into a list of words
b. Changing the person of each pronoun in the list
c. Converting the list back to a string
d. Prepending a qualifier to the string to create a question
e. Printing the result
or
Printing a randomly chosen hedge
Steps 1 and 2 are repeated until the patient enters ‘quit’
Data Structures for the
Program
 A list of qualifiers to be chosen at
random

 A list of hedges to be chosen at


random

 A dictionary of pronouns and their


replacements
Data Structures for the Program
qualifiers = ['Why do you say that ',
'You seem to think that ',
'Did I just hear you say that ']

replacements = {'I': 'you', 'me': 'you', 'my': 'your',


'we': 'you', 'us': 'you'}

The function random.choice returns a randomly selected item


from a given sequence

import random

print(random.choice(qualifiers))
The Main Loop
def main():
"""Handles user interaction with the program."""
print('Good morning, how can I help you today?')
while True:
sentence = input('> ')
if sentence.upper() == 'QUIT':
break
print(reply(sentence))
print('Have a nice day!')

The function main handles the interaction with the user


The function reply transforms the patient’s input into the
doctor’s reply and returns it
Defining reply
def reply(sentence):
"""Returns a reply to the sentence."""
return random.choice(qualifiers) + changePerson(sentence)

reply prepends a randomly chosen qualifier to the result of


changing persons in the patient’s input sentence

The result returned is in the form of a question that includes most


of the content of the patient’s input sentence
The Strategy for changePerson
1. Explode the sentence into a list of words

2. Loop through the list and build a new list as we go

3. If the word in the input list is in the replacements


dictionary, add its replacement to the new list

4. Otherwise, just add the original word to the new list

5. When the loop is finished, congeal the new list to a


string of words and return it
Defining changePerson
def changePerson(sentence):
"""Returns the sentence with pronouns changed."""
oldlist = sentence.split()
newlist = []
for word in oldlist:
if word in replacements:
newlist.append(replacements[word])
else:
newlist.append(word)
return " ".join(newlist)

Instead of the if-else statement, we could


accomplish the replacement more simply using get:

newlist.append(replacements.get(word, word))
Defining changePerson
def changePerson(sentence):
"""Returns the sentence with pronouns changed."""
oldlist = sentence.split()
newlist = []
for word in oldlist:
newlist.append(replacements.get(word, word))
return " ".join(newlist)

Instead of using an if-else statement, we could


accomplish the replacement more simply by using get
Improvements
 Add hedges

 Keep track of earlier patient inputs,


so the doctor can refer back to them

 Spot keywords in a patient’s reply,


and respond with associated
sentences
Thank You

Let's get started!

2023-12-14 Computer Sys. And Programming

You might also like