Regular Expressions Solve the following problems using regular expressions. Your code should be submitted in a .py file and include both the regular expression searches and comments that provide the...

1 answer below »
need help with writing the code for this


Regular Expressions Solve the following problems using regular expressions. Your code should be submitted in a .py file and include both the regular expression searches and comments that provide the output. Also include comments about the structure of your regular expression describing the reasoning of how it helps to answer the question. 1. Write a regular expression that finds words of length n or longer. Use this regular expression to find out what is the longest word used in shakespeare.txt (from zip for class). 2. In the shakespeare.txt file the play titles are printed on their own lines and are written in all capital letters. Write a regular expression to pull exactly (no more and no less than) the 37 titles from the file. (HINT: For some reason the title for Henry VIII starts with a space and don't forget punctuation) 3. Write a regular expression to find all words with 8 or more vowels (not including y) in unixdict.txt . 4. What word has the most consecutive consonants (including y as a consonant) in unixdict.txt? 5. How many words in unixdict.txt contain the word cat or dog? 10th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th a a&m a&p a's aaa aaas aarhus aaron aau aba ababa aback abacus abalone abandon abase abash abate abater abbas abbe abbey abbot abbott abbreviate abc abdicate abdomen abdominal abduct abe abed abel abelian abelson aberdeen abernathy aberrant aberrate abet abetted abetting abeyance abeyant abhorred abhorrent abide abidjan abigail abject ablate ablaze able ablution abner abnormal abo aboard abode abolish abolition abominable abominate aboriginal aborigine aborning abort abound about above aboveboard aboveground abovementioned abrade abraham abram abramson abrasion abrasive abreact abreast abridge abridgment abroad abrogate abrupt abscess abscissa abscissae absence absent absentee absenteeism absentia absentminded absinthe absolute absolution absolve absorb absorbent absorption absorptive abstain abstention abstinent abstract abstracter abstractor abstruse absurd abuilding abundant abusable abuse abusive abut abutted abutting abysmal abyss abyssinia ac academe academia academic academician academy acadia acanthus acapulco accede accelerate accelerometer accent accentual accentuate accept acceptant acceptor access accessible accession accessory accident accidental accipiter acclaim acclamation acclimate accolade accommodate accompaniment accompanist accompany accomplice accomplish accord accordant accordion accost account accountant accra accredit accreditate accreditation accretion accrual accrue acculturate accumulate accuracy accurate accusation accusative accusatory accuse accustom ace acerbic acerbity acetate acetic acetone acetylene ache achieve achilles aching achromatic acid acidic acidulous ackerman ackley acknowledge acknowledgeable acm acme acolyte acorn acoustic acquaint acquaintance acquiesce acquiescent acquire acquisition acquisitive acquit acquittal acquitting acre acreage acrid acrimonious acrimony acrobacy acrobat acrobatic acronym acropolis across acrylate acrylic acs act actaeon actinic actinide actinium actinolite actinometer activate activation activism acton actor actress acts actual actuarial actuate acuity acumen acute acyclic ad ada adage adagio adair adam adamant adams adamson adapt adaptation adaptive add added addend addenda addendum addict addis addison addition additional additive addle address addressee addressograph adduce adelaide adele adelia aden adenine adenoma adenosine adept adequacy adequate adhere adherent adhesion adhesive adiabatic adieu adipic adirondack adjacent adject adjectival adjective adjoin adjoint adjourn adjudge adjudicate adjunct adjust adjutant adkins adler administer administrable administrate administratrix admiral admiralty admiration admire admissible admission admit admittance admitted admitting admix admixture admonish admonition ado adobe adolescent adolph adolphus adonis adopt adoption adoptive adore adorn adposition adrenal adrenaline adrian adriatic adrienne adrift adroit adsorb adsorbate adsorption adsorptive adulate adult adulterate adulterous adultery adulthood advance advantage advantageous advent adventitious adventure adventurous adverb adverbial adversary adverse advert advertise advice advisable advise advisee advisor advisory advocacy advocate aegean aegis aeneas aeneid aeolian aeolus aerate aerial aerobacter aerobic aerodynamic aerogene aeronautic aerosol aerospace aeschylus aesthete aesthetic afar affable affair affect affectate affectation affectionate afferent affiance affidavit affiliate affine affinity affirm affirmation affirmative affix afflict affluence affluent afford afforest afforestation affricate affront afghan afghanistan aficionado afield afire aflame afloat afoot aforementioned aforesaid aforethought afoul afraid afresh africa afro aft aftereffect afterglow afterimage afterlife aftermath afternoon afterthought afterward afterword again against agamemnon agate agatha agave age agee agenda agent agglomerate agglutinate agglutinin aggravate aggregate aggression aggressive aggressor aggrieve aghast agile aging agitate agleam agnes agnew agnomen agnostic ago agone agony agouti agrarian agree agreeable agreed agreeing agribusiness agricola agricultural agriculture agrimony ague agway ah ahead ahem ahmadabad ahmedabad ahoy aid aida aide aides aiken ail ailanthus aile aileen aileron aim ain't ainu air airborne aircraft airdrop airedale aires airfare airfield airflow airfoil airframe airlift airline airlock airmail airman airmass airmen airpark airplane airport airspace airspeed airstrip airtight airway airy aisle aitken ajar ajax ak akers akin akron al ala alabama alabamian alabaster alacrity alai alameda alamo alan alarm alaska alb alba albacore albania albanian albany albatross albeit alberich albert alberta alberto albrecht albright album albumin albuquerque alcestis alchemy alcmena alcoa alcohol alcoholic alcoholism alcott alcove aldebaran aldehyde alden alder alderman aldermen aldrich aldrin ale alec aleck aleph alert alewife alex alexander alexandra alexandre alexandria alexei alexis alfalfa alfonso alfred alfredo alfresco alga algae algaecide algal algebra algebraic algenib alger algeria algerian algiers alginate algol algonquin algorithm algorithmic alhambra ali alia alias alibi alice alicia alien alienate alight align alike alimony aliphatic aliquot alison alistair alive alizarin alkali alkaline alkaloid alkane alkene all allah allan allay allegate allegation allege allegheny allegiant allegoric allegory allegra allegro allele allemand allen allentown allergic allergy alleviate alley alleyway alliance allied alligator allis allison alliterate allocable allocate allot allotropic allotted allotting allow allowance alloy allspice allstate allude allure allusion allusive alluvial alluvium ally allyl allyn alma almaden almagest almanac almighty almond almost aloe aloft aloha alone along alongside aloof aloud alp alpenstock alpert alpha alphabet alphabetic alphameric alphanumeric alpheratz alphonse alpine alps already alsatian also alsop altair altar alter alterate alteration altercate alterman altern alternate althea although altimeter altitude alto altogether alton altruism altruist alum alumina aluminate alumna alumnae alumni alumnus alundum alva alvarez alveolar alveoli alveolus alvin alway always alyssum am ama amadeus amalgam amalgamate amanita amanuensis amaranth amarillo amass amateur amateurish amatory amaze amazon ambassador amber ambiance ambidextrous ambient ambiguity ambiguous ambition ambitious ambivalent amble ambling ambrose ambrosia ambrosial ambulant ambulate ambulatory ambuscade ambush amelia ameliorate amen amend amende amerada america american americana americanism americium ames ameslan amethyst amethystine amherst ami amicable amid amide amidst amigo amino aminobenzoic amiss amity amman ammerman ammeter ammo ammonia ammoniac ammonium ammunition amnesia amoco amoeba amoebae amok among amongst amoral amorous amorphous amort amos amount amp amperage ampere ampersand ampex amphetamine amphibian amphibious amphibole amphibology amphioxis ample amplifier amplify amplitude amply amputate amputee amra amsterdam amtrak amulet amuse amy amygdaloid an ana anabaptist anabel anachronism anachronistic anaconda anaerobic anaglyph anagram anaheim analeptic analgesic analogous analogue analogy analyses analysis analyst analytic anamorphic anaplasmosis anarch anarchic anarchy anastasia anastigmat anastigmatic anastomosis anastomotic anathema anatole anatomic anatomy ancestor ancestral ancestry anchor anchorage anchorite anchoritism anchovy ancient ancillary and andean andersen anderson andes andesine andesite andiron andorra andover andre andrea andrei andrew andrews andromache andromeda andy anecdotal anecdote anemone anent anew angel angela angeles angelfish angelic angelica angelina angeline angelo anger angie angiosperm angle angles anglican anglicanism angling anglo anglophobia angola angora angry angst angstrom anguish angular angus anharmonic anheuser anhydride anhydrite anhydrous ani aniline animadversion animadvert animal animate animism animosity anion anionic anise aniseikonic anisotropic anisotropy anita ankara ankle ann anna annal annale annalen annals annapolis anne anneal annette annex annie annihilate anniversary annotate announce annoy annoyance annual annuity annul annular annuli annulled annulling annulus annum annunciate anode anodic anomalous anomaly anomie anonymity anonymous anorexia anorthic anorthite anorthosite another anselm anselmo ansi answer ant antacid antaeus antagonism antagonist antagonistic antarctic antarctica antares ante anteater antebellum antecedent antedate antelope antenna antennae anterior anteroom anthem anther anthology anthony anthracite anthracnose anthropogenic anthropology anthropomorphic anthropomorphism anti antic anticipate anticipatory antietam antigen antigone antigorite antimony antioch antipasto antipathy antiperspirant antiphonal antipode antipodean antipodes antiquarian antiquary antiquated antique antiquity antisemite antisemitic antisemitism antithetic antler antoine antoinette anton antonio antony antonym antwerp anus anvil anxiety anxious any anybody anybody'd anyhow anyone anyplace anything anyway anywhere aorta apace apache apart apartheid apathetic apathy apatite ape aperiodic aperture apex aphasia aphasic aphelion aphid aphorism aphrodite apices apiece aplomb apocalypse apocalyptic apocrypha apocryphal apogee apollo apollonian apologetic apologia apology apostate apostle apostolic apostrophe apothecary apothegm apotheosis appalachia appall appanage apparatus apparel apparent apparition appeal appear appearance appeasable appease appellant appellate append appendage appendices appendix apperception appertain appetite appian applaud applause apple appleby applejack appleton appliance applicable applicant applicate application applied applique apply appoint appointe appointee apport apportion apposite apposition appraisal appraise appreciable appreciate apprehend apprehension apprehensive apprentice apprise approach approbation appropriable appropriate approval approve approximable approximant approximate apr apricot april apron apropos aps apse apt aptitude aqua aquarium aquarius aquatic aqueduct aqueous aquila aquinas ar arab arabesque arabia arabic araby arachne arachnid arbiter arbitrage arbitrary arbitrate arboreal arboretum arbutus arc arcade arcadia arcana arcane arccos arccosine arch archae archaic archaism archangel archbishop archdiocese archenemy archer archery archetype archetypical archfool archibald archimedes arching archipelago architect architectonic architectural architecture archival archive arcing arclength arcsin arcsine arctan arctangent arctic arcturus arden ardency ardent arduous are area areaway areawide aren't arena arenaceous arequipa ares argentina argillaceous arginine argive argo argon argonaut argonne argot argue argument argumentation argumentative argus arhat ariadne arianism arid aries arise arisen aristocracy aristocrat aristocratic aristotelean aristotelian aristotle arithmetic arizona ark arkansan arkansas arlen arlene arlington arm armada armadillo armageddon armament armata armature armchair armco armenia armenian armful armhole armillaria armistice armload armoire armonk armour armpit armstrong army arnold aroma aromatic arose around arousal arouse arpa arpeggio arrack arragon arraign arrange arrangeable array arrear arrest arrhenius arrival arrive arrogant arrogate arrow arrowhead arrowroot arroyo arsenal arsenate arsenic arsenide arsine arson art artemis artemisia arterial arteriole arteriolosclerosis arteriosclerosis artery artful arthritis arthur artichoke article articulate articulatory artie artifact artifice artificial artillery artisan artistry arturo artwork arty aruba arum aryl as asbestos ascend ascendant ascension ascent ascertain ascetic asceticism ascomycetes ascribe ascription aseptic asexual ash ashame ashamed ashen asher asheville ashland ashley ashman ashmen ashmolean ashore ashtray ashy asia asiatic aside asilomar asinine ask askance askew asleep asocial asparagine asparagus aspartic aspect aspen asperity aspersion asphalt aspheric asphyxiate aspidistra aspirant aspirate aspire aspirin asplenium ass assai assail assailant assam assassin assassinate assault assay assemblage assemble assent assert assess assessor asset assiduity assiduous assign assignation assignee assimilable assimilate assist assistant associable associate assonant assort assuage assume assumption assurance assure assyria assyriology astarte astatine aster asteria asterisk asteroid asteroidal asthma astigmat astigmatic astigmatism astm astonish astor astoria astound astraddle astral astray astride astringent astrology astronaut astronautic astronomer astronomic astronomy astrophysical astrophysicist astrophysics astute asuncion asunder asylum asymmetry asymptote asymptotic asynchronous asynchrony at at&t atalanta atavism atavistic atchison ate athabascan atheism atheist athena athenian athens athlete athletic athwart atkins atkinson atlanta atlantes atlantic atlantica atlantis atlas atmosphere atmospheric atom atomic atonal atone atop atreus atrium atrocious atrocity atrophic atrophy atropos attach attache attack attain attainder attempt attend attendant attendee attention attentive attenuate attest attestation attic attica attire attitude attitudinal attorney attract attribute attribution attributive attrition attune atwater atwood atypic auberge aubrey auburn auckland auction auctioneer audacious audacity audible audience audio audiotape audiovisual audit audition auditor auditorium auditory audrey audubon auerbach aug augean augend auger augite augment augmentation augur august augusta augustan augustine augustus auk aunt auntie aura aural aurelius aureomycin auric auriga aurochs aurora auschwitz auspices auspicious austenite austere austin australia australis australite austria authentic authenticate author authoritarian authoritative autism autistic auto autobiography autoclave autocollimate autocorrelate autocracy autocrat autocratic autograph automat automata automate automatic automaton automobile automorphic automorphism automotive autonomic autonomous autonomy autopsy autosuggestible autotransformer autumn autumnal auxiliary avail avalanche avarice avaricious ave avenge aventine avenue aver average averred averring averse aversion avert avertive avery avesta aviary aviate aviatrix avid avionic avis aviv avocado avocate avocation avocet avogadro avoid avoidance avon avow avowal avuncular await awake awaken award aware awash away awe awesome awful awhile awkward awl awn awoke awry ax axe axes axial axiology axiom axiomatic axis axisymmetric axle axolotl axon aye ayers aylesbury az azalea azerbaijan azimuth azimuthal aztec aztecan azure
Answered Same DayMar 27, 2021

Answer To: Regular Expressions Solve the following problems using regular expressions. Your code should be...

Devanshu answered on Mar 28 2021
132 Votes
import re
import os
def findwords():
n = int(input("Enter the length of words you want to check out fo
r :"))
infile = open('shakespeare.txt', 'r')
fread = infile.read()
words = re.findall('^[A-Za-z]{' + str(n) + ',}', fread, re.M)
print(words)
print(len(words))
if words:
print("The longest word in this file is", max(words, key=len))
infile.close()
def findtitles():
infile = open('shakespeare.txt', 'r')
lines = infile.readlines()
count = 0
rx = re.compile(r"^([A-Z ,\':;-]+[A-Z ,\':;-]+[A-Z ,\':;-]+[A-Z ,\':;-]+$)", re.M)
for line in lines:
str = "".join(line)
Title = rx.findall(str)
if len(Title) == 1:
if len(re.findall(r"^ $", str)) == 0:
count += 1
print(line, " \t%s" % count)
print("These are the %d titles in the shakespeare.txt" % count)
infile.close()
def vowels():
print("Here are the words that contains 8 or more than 8 vowels:-")
vowels = re.compile(r"^([^aieou]*[aieou]){8,}[^aieou]*$", re.I)
nonword =...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here