python辅导、辅导Random Sentence Generator

- 首页 >> Python编程

Question 1 - Random Sentence Generator - 7 marksWrite a program that reads in files of words and produces random but structurally correct Englishsentences, according to the syntax (rules of grammar) specified on the next page.Here is the output of a demo program. These sentences are correctly structured English but (usually) makeabsolutely no sense (but are often fun :-)It is commonly believed that your ghastly Mortician deliberately befriends my annoying bulb.Lo! our green lecturer often hibernates.This foreign burglar usually cooks and ate the flesh of her inconceivable colour.Indeed, the orbiting boy inexorably recognizes this half-hidden monstrosity.My vaporized model knowingly reaches an understanding with his dainty terror.Additional data files:• RandomSentenceWordlists.zip on Stream has files for each class of word,e.g. Nouns.txt, Adjectives.txt, …• Important: put the files from Wordlists.zip into the same folder as your Python file.CommandsMake the following commands available using a menu and prompt for a command. The commands can beupper or lower case (e.g. e or E) or either. It'll be easier if you implement the commands in order (L first…)CMD EffectL Load all the files of words from disk.T Test – display the first word from each list to make sure they've been loaded.E Easy sentence: display a two word sentence - a randomly selected noun followedby a randomly selected intransitive verb and then a full stop.S new Sentence - generate & display a sentence conforming to the grammar definedin the 'Use this grammar to make your sentences' section on the next page.If the wordlists haven't been loaded, display an error message.Q Quit the program.For full marks• the sentences should be capitalised correctly and have a trailing full stop.• the sentences generated by the “S” command should conform to the specified grammar• meaningful variable names should be used & any complex parts should be commentedThe explanation on the next page is a little wordy but the idea underlying is simple – you randomly selectwords from appropriate word lists and combine them so they're correct English sentences.159.171 – Assignment 3 1 © Giovanni Moretti 2017Defining the Structure of SentencesWe all know what sounds right as a sentence, but to create correct sentences using a program, we have tobe more precise.Below, I've defined a grammar that specifies the syntax (i.e. the structure) of valid tiny sentences.What the symbols mean when defining a grammar: ::= is read as “is defined as”. Square brackets [ ] around an item mean that item is optional (it can be omitted). the vertical bar | means OR (choose the item to the left OR the item right) Angle brackets (e.g. < > ) around an item means it’s a placeholder that will be replaced later.EXAMPLE: to illustrate how a grammar can be defined and used, say we have four named lists ofwords, (e.g. <Noun> is the name of the first group) <Noun-marker> our, my, the <Adjective> red, huge, slimy <Noun> cat, fire, sky <Verb> eats, climbs, digs upand the following rule defines valid Noun-Phrases:<Noun-Phrase> ::= [ <Noun-marker> ] [ <Adjective> ] <Noun>Square brackets around an item means it's optional, so both the Noun-marker and Adjective can beomitted. Therefore the following five noun phrases all comply with the above Noun-Phrase definition: 1) cat 2) our fire 3) our slimy sky (4) huge fire (5) my red catJust for this example, let the definition for Sentence be: Sentence ::= Noun-Phrase Verb Noun-phrase the red cat eats our slimy skyour sky climbs the huge firemy cat digs up the red skyCapitalise the first word & add a full stop, and each of these three lines is a silly but valid sentence.Use this grammar to make your sentencesThe following grammar defines the structure of a sentence for your answer to this assignment question.<Sentence>::= [<Lead-in>] <Noun-Phrase> [<Adverb>] <Verb-Phrase> .Read this as: “a sentence is defined as a Lead-in (which, because is surrounded by square brackets, isoptional) followed by a Noun-phrase, an optional Adverb, then a Verb-Phrase and a full stop”.<Noun-Phrase> ::= <Noun-marker> [ <Adjective> ] <Noun><Verb-Phrase> ::= <Intransitive-verb> | <Transitive-verb> <Noun-phrase> is read as: "A verb phrase can be an intransitive verb OR a transitive-verb1 followed by a noun phrase"Where <Noun> means any line from the Nouns.txt file, and likewise for the others (e.g. <Adjectives> ...)1 transitive-verbs take an object (there must be a noun after the verb) e.g. the cat bounced the ball159.171 – Assignment 3 2 © Giovanni Moretti 2017Suggestions Optional items are included 50% of the time. To control this, you can usethe random.random() function which returns a real number somewhere between 0 and 1, orrandom.choice( ['heads', 'tails'] ) - try it and see what it doesDon't forget to import the random module There are many ways to build the sentence: you can print out each word as you go. This method is simple but has the limitation thatyou never have the complete sentence as a string. you can build up the sentence by making a string that gets longer as you add the next partof the sentence :e.g. s = a random selection from Leadins = s + random selection from NounMarker # and keep adding you could add the pieces to a list and then join them together using '' '.join(your-list) Your program will have a cleaner structure and be easier to follow if you create functions for<noun-phrase> and <verb-phrase>, and possibly <sentence> as well. You may find s.capitalize() useful.Possible extensionsThis is fun program and there are lots of way you could extend it. You could:• remember a noun from one sentence and reusing it in the next sentences• there's a conjunction wordlist (e.g. and) which isn't currently used. You could make your programcreate paragraphs by creating multiple sentences joined with conjunctions, possibly repeating thenouns to provide some continuity• make it remember all the sentences created in a list.• add a Favourites command which adds the most recently created sentence to a list of favourites.159.171 – Assignment 3 3 © Giovanni Moretti 2017Question 2 – An Addressbook – 7 marksUsing a dictionary indexed by nickname (a short favourite name), write a simple address book thatlets you save these contact details.• nickname (can be anything you like)• name• address• phone-noEach dictionary entry contains a dictionary of the details of that person, so names['Tom'] # will return the dictionary that contains all of Tom's details,and contacts = names['Tom"] address = contacts['address']or simply address = contacts['Tom']['address']will return Tom's addressThe program first displays a menu (something like that shown below) and carries out the appropriateaction depending on which letter the user types, and then redisplays the menu:*** My Contacts *** f – find a – add new entry d – delete l – list all q – quitcommand: ?add prompt separately for each of name, address, phone-no and nickname. Then save all of thesefields into a data structure. A dictionary is recommended but a list will also work.find prompt for a nickname, then search for the name, address and phone number of the personwith this nickname in your addressbook and display their details. Make the search is caseinsensitivei.e. only the letters matter, not whether they're upper or lower casedelete prompt for a nickname, then find and display the related entry. Ask the user if this is thecorrect one to be deleted. If they reply "yes" delete it.list all As expected list all the entries, numbered sequentially. Display all the fields and format themfor easy reading. Some possibilities are shown below.Across Nick Name Address Phone No1 sue Sue Williams 104 Broadway, Pnth 021-333-55552 bob Robert Levine 25 Fitzherbert Ave 06-355-6666Down1 sue Sue Williams 25 Broadway, PNth 021-333-55552 bob Robert Levine 104 Fitzherbert Ave 06-355-6666159.171 – Assignment 3 4 © Giovanni Moretti 2017Does the name exist?When adding entries, as soon as the nickname is given, check to see if that nickname in the addressbook.If so, ask if the new entry should replace the existing one for that nickname. If the answer is no, thenprompt again for a new nickname. To abort the add command (and find/delete), simply enter an emptystring for the nickname.Be sure to an appropriate message if the user tries to find or delete an entry and the nickname isn't in use.IMPORTANT: make sure that you use functions, usually one for each of the commands. You can ofcourse, create any additional functions that you think will help to simplify or clarify your code.The Addressbook - Getting Started:1. get the menu going and then create a function for each of list-all, add, … Initially, simply put aprint inside each function, e.g. for the addEntry function, put print("You called ADD"). You cantest each command – they'll simply print out a message.2. using an assignment statement, manually create a tiny addressbook containing a two or threeentries3. get the list-all command going. You can use this to view your manually created addressbook andeffects of the later commands4. then work on add, find and deleteOptional (you can get full marks without doing this): you could try adding a s (search) command thatsearches for and displays all entries that have the search string in any of the fields (not just the nickname).What and how to submitHow: ALL submissions must be via Stream (not email) using the Assignment 3 submission link.What: Submit your Python programs, each named with .py extensions. You should have three .py files tosubmit, one for each question.Do not submit Word documents (.doc or .docx) or .zip files.Check that: all programs should display your name and ID number when starting. that your files have a .py extension159.171 – Assignment 3 5 © Giovanni Moretti 2017

站长地图