From 7f2a7bafc6de99a4cdf897db01a262192fcb090e Mon Sep 17 00:00:00 2001 From: elena5100 <194572363+elena5100@users.noreply.github.com> Date: Tue, 21 Jan 2025 11:46:58 -0800 Subject: [PATCH 1/4] add my name --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e57375e..0d8cdd7 100644 --- a/README.md +++ b/README.md @@ -110,4 +110,6 @@ Consider doing any of the following (some are very hard!): ## Submitting Submit your project by making a PR and copying the link to the canvas assignment. -TURN SOMETHING IN BY THE DUE DATE EVEN IF YOU'RE NOT FINISHED. \ No newline at end of file +TURN SOMETHING IN BY THE DUE DATE EVEN IF YOU'RE NOT FINISHED. + +shams \ No newline at end of file From 7695191e8156f412deccc509c5c903ba5be8e450 Mon Sep 17 00:00:00 2001 From: elena5100 <194572363+elena5100@users.noreply.github.com> Date: Wed, 29 Jan 2025 22:29:09 -0800 Subject: [PATCH 2/4] Updated LowercaseSentenceTokenizer and test cases for Waves 1, 2, and 3 --- keatsTraining.txt | 602 ++++++++---------------- src/LowercaseSentenceTokenizer.java | 42 +- src/LowercaseSentenceTokenizerTest.java | 10 + 3 files changed, 243 insertions(+), 411 deletions(-) diff --git a/keatsTraining.txt b/keatsTraining.txt index 8a15084..fb0db76 100644 --- a/keatsTraining.txt +++ b/keatsTraining.txt @@ -1,407 +1,195 @@ -Upon a time, before the faery broods -Drove Nymph and Satyr from the prosperous woods, -Before King Oberon's bright diadem, -Sceptre, and mantle, clasp'd with dewy gem, -Frighted away the Dryads and the Fauns -From rushes green, and brakes, and cowslip'd lawns, -The ever-smitten Hermes empty left -His golden throne, bent warm on amorous theft: -From high Olympus had he stolen light, -On this side of Jove's clouds, to escape the sight -Of his great summoner, and made retreat -Into a forest on the shores of Crete. -For somewhere in that sacred island dwelt -A nymph, to whom all hoofed Satyrs knelt; -At whose white feet the languid Tritons poured -Pearls, while on land they wither'd and adored. -Fast by the springs where she to bathe was wont, -And in those meads where sometime she might haunt, -Were strewn rich gifts, unknown to any Muse, -Though Fancy's casket were unlock'd to choose. -Ah, what a world of love was at her feet! -So Hermes thought, and a celestial heat -Burnt from his winged heels to either ear, -That from a whiteness, as the lily clear, -Blush'd into roses 'mid his golden hair, -Fallen in jealous curls about his shoulders bare. -From vale to vale, from wood to wood, he flew, -Breathing upon the flowers his passion new, -And wound with many a river to its head, -To find where this sweet nymph prepar'd her secret bed: -In vain; the sweet nymph might nowhere be found, -And so he rested, on the lonely ground, -Pensive, and full of painful jealousies -Of the Wood-Gods, and even the very trees. -There as he stood, he heard a mournful voice, -Such as once heard, in gentle heart, destroys -All pain but pity: thus the lone voice spake: -"When from this wreathed tomb shall I awake! -When move in a sweet body fit for life, -And love, and pleasure, and the ruddy strife -Of hearts and lips! Ah, miserable me!" -The God, dove-footed, glided silently -Round bush and tree, soft-brushing, in his speed, -The taller grasses and full-flowering weed, -Until he found a palpitating snake, -Bright, and cirque-couchant in a dusky brake. - -She was a gordian shape of dazzling hue, -Vermilion-spotted, golden, green, and blue; -Striped like a zebra, freckled like a pard, -Eyed like a peacock, and all crimson barr'd; -And full of silver moons, that, as she breathed, -Dissolv'd, or brighter shone, or interwreathed -Their lustres with the gloomier tapestries-- -So rainbow-sided, touch'd with miseries, -She seem'd, at once, some penanced lady elf, -Some demon's mistress, or the demon's self. -Upon her crest she wore a wannish fire -Sprinkled with stars, like Ariadne's tiar: -Her head was serpent, but ah, bitter-sweet! -She had a woman's mouth with all its pearls complete: -And for her eyes: what could such eyes do there -But weep, and weep, that they were born so fair? -As Proserpine still weeps for her Sicilian air. -Her throat was serpent, but the words she spake -Came, as through bubbling honey, for Love's sake, -And thus; while Hermes on his pinions lay, -Like a stoop'd falcon ere he takes his prey. - -"Fair Hermes, crown'd with feathers, fluttering light, -I had a splendid dream of thee last night: -I saw thee sitting, on a throne of gold, -Among the Gods, upon Olympus old, -The only sad one; for thou didst not hear -The soft, lute-finger'd Muses chaunting clear, -Nor even Apollo when he sang alone, -Deaf to his throbbing throat's long, long melodious moan. -I dreamt I saw thee, robed in purple flakes, -Break amorous through the clouds, as morning breaks, -And, swiftly as a bright Phoebean dart, -Strike for the Cretan isle; and here thou art! -Too gentle Hermes, hast thou found the maid?" -Whereat the star of Lethe not delay'd -His rosy eloquence, and thus inquired: -"Thou smooth-lipp'd serpent, surely high inspired! -Thou beauteous wreath, with melancholy eyes, -Possess whatever bliss thou canst devise, -Telling me only where my nymph is fled,-- -Where she doth breathe!" "Bright planet, thou hast said," -Return'd the snake, "but seal with oaths, fair God!" -"I swear," said Hermes, "by my serpent rod, -And by thine eyes, and by thy starry crown!" -Light flew his earnest words, among the blossoms blown. -Then thus again the brilliance feminine: -"Too frail of heart! for this lost nymph of thine, -Free as the air, invisibly, she strays -About these thornless wilds; her pleasant days -She tastes unseen; unseen her nimble feet -Leave traces in the grass and flowers sweet; -From weary tendrils, and bow'd branches green, -She plucks the fruit unseen, she bathes unseen: -And by my power is her beauty veil'd -To keep it unaffronted, unassail'd -By the love-glances of unlovely eyes, -Of Satyrs, Fauns, and blear'd Silenus' sighs. -Pale grew her immortality, for woe -Of all these lovers, and she grieved so -I took compassion on her, bade her steep -Her hair in weird syrops, that would keep -Her loveliness invisible, yet free -To wander as she loves, in liberty. -Thou shalt behold her, Hermes, thou alone, -If thou wilt, as thou swearest, grant my boon!" -Then, once again, the charmed God began -An oath, and through the serpent's ears it ran -Warm, tremulous, devout, psalterian. -Ravish'd, she lifted her Circean head, -Blush'd a live damask, and swift-lisping said, -"I was a woman, let me have once more -A woman's shape, and charming as before. -I love a youth of Corinth--O the bliss! -Give me my woman's form, and place me where he is. -Stoop, Hermes, let me breathe upon thy brow, -And thou shalt see thy sweet nymph even now." -The God on half-shut feathers sank serene, -She breath'd upon his eyes, and swift was seen -Of both the guarded nymph near-smiling on the green. -It was no dream; or say a dream it was, -Real are the dreams of Gods, and smoothly pass -Their pleasures in a long immortal dream. -One warm, flush'd moment, hovering, it might seem -Dash'd by the wood-nymph's beauty, so he burn'd; -Then, lighting on the printless verdure, turn'd -To the swoon'd serpent, and with languid arm, -Delicate, put to proof the lythe Caducean charm. -So done, upon the nymph his eyes he bent -Full of adoring tears and blandishment, -And towards her stept: she, like a moon in wane, -Faded before him, cower'd, nor could restrain -Her fearful sobs, self-folding like a flower -That faints into itself at evening hour: -But the God fostering her chilled hand, -She felt the warmth, her eyelids open'd bland, -And, like new flowers at morning song of bees, -Bloom'd, and gave up her honey to the lees. -Into the green-recessed woods they flew; -Nor grew they pale, as mortal lovers do. - -Left to herself, the serpent now began -To change; her elfin blood in madness ran, -Her mouth foam'd, and the grass, therewith besprent, -Wither'd at dew so sweet and virulent; -Her eyes in torture fix'd, and anguish drear, -Hot, glaz'd, and wide, with lid-lashes all sear, -Flash'd phosphor and sharp sparks, without one cooling tear. -The colours all inflam'd throughout her train, -She writh'd about, convuls'd with scarlet pain: -A deep volcanian yellow took the place -Of all her milder-mooned body's grace; -And, as the lava ravishes the mead, -Spoilt all her silver mail, and golden brede; -Made gloom of all her frecklings, streaks and bars, -Eclips'd her crescents, and lick'd up her stars: -So that, in moments few, she was undrest -Of all her sapphires, greens, and amethyst, -And rubious-argent: of all these bereft, -Nothing but pain and ugliness were left. -Still shone her crown; that vanish'd, also she -Melted and disappear'd as suddenly; -And in the air, her new voice luting soft, -Cried, "Lycius! gentle Lycius!"--Borne aloft -With the bright mists about the mountains hoar -These words dissolv'd: Crete's forests heard no more. - -Whither fled Lamia, now a lady bright, -A full-born beauty new and exquisite? -She fled into that valley they pass o'er -Who go to Corinth from Cenchreas' shore; -And rested at the foot of those wild hills, -The rugged founts of the Peræan rills, -And of that other ridge whose barren back -Stretches, with all its mist and cloudy rack, -South-westward to Cleone. There she stood -About a young bird's flutter from a wood, -Fair, on a sloping green of mossy tread, -By a clear pool, wherein she passioned -To see herself escap'd from so sore ills, -While her robes flaunted with the daffodils. - -Ah, happy Lycius!--for she was a maid -More beautiful than ever twisted braid, -Or sigh'd, or blush'd, or on spring-flowered lea -Spread a green kirtle to the minstrelsy: -A virgin purest lipp'd, yet in the lore -Of love deep learned to the red heart's core: -Not one hour old, yet of sciential brain -To unperplex bliss from its neighbour pain; -Define their pettish limits, and estrange -Their points of contact, and swift counterchange; -Intrigue with the specious chaos, and dispart -Its most ambiguous atoms with sure art; -As though in Cupid's college she had spent -Sweet days a lovely graduate, still unshent, -And kept his rosy terms in idle languishment. - -Why this fair creature chose so fairily -By the wayside to linger, we shall see; -But first 'tis fit to tell how she could muse -And dream, when in the serpent prison-house, -Of all she list, strange or magnificent: -How, ever, where she will'd, her spirit went; -Whether to faint Elysium, or where -Down through tress-lifting waves the Nereids fair -Wind into Thetis' bower by many a pearly stair; -Or where God Bacchus drains his cups divine, -Stretch'd out, at ease, beneath a glutinous pine; -Or where in Pluto's gardens palatine -Mulciber's columns gleam in far piazzian line. -And sometimes into cities she would send -Her dream, with feast and rioting to blend; -And once, while among mortals dreaming thus, -She saw the young Corinthian Lycius -Charioting foremost in the envious race, -Like a young Jove with calm uneager face, -And fell into a swooning love of him. -Now on the moth-time of that evening dim -He would return that way, as well she knew, -To Corinth from the shore; for freshly blew -The eastern soft wind, and his galley now -Grated the quaystones with her brazen prow -In port Cenchreas, from Egina isle -Fresh anchor'd; whither he had been awhile -To sacrifice to Jove, whose temple there -Waits with high marble doors for blood and incense rare. -Jove heard his vows, and better'd his desire; -For by some freakful chance he made retire -From his companions, and set forth to walk, -Perhaps grown wearied of their Corinth talk: -Over the solitary hills he fared, -Thoughtless at first, but ere eve's star appeared -His phantasy was lost, where reason fades, -In the calm'd twilight of Platonic shades. -Lamia beheld him coming, near, more near-- -Close to her passing, in indifference drear, -His silent sandals swept the mossy green; -So neighbour'd to him, and yet so unseen -She stood: he pass'd, shut up in mysteries, -His mind wrapp'd like his mantle, while her eyes -Follow'd his steps, and her neck regal white -Turn'd--syllabling thus, "Ah, Lycius bright, -And will you leave me on the hills alone? -Lycius, look back! and be some pity shown." -He did; not with cold wonder fearingly, -But Orpheus-like at an Eurydice; -For so delicious were the words she sung, -It seem'd he had lov'd them a whole summer long: -And soon his eyes had drunk her beauty up, -Leaving no drop in the bewildering cup, -And still the cup was full,--while he, afraid -Lest she should vanish ere his lip had paid -Due adoration, thus began to adore; -Her soft look growing coy, she saw his chain so sure: -"Leave thee alone! Look back! Ah, Goddess, see -Whether my eyes can ever turn from thee! -For pity do not this sad heart belie-- -Even as thou vanishest so I shall die. -Stay! though a Naiad of the rivers, stay! -To thy far wishes will thy streams obey: -Stay! though the greenest woods be thy domain, -Alone they can drink up the morning rain: -Though a descended Pleiad, will not one -Of thine harmonious sisters keep in tune -Thy spheres, and as thy silver proxy shine? -So sweetly to these ravish'd ears of mine -Came thy sweet greeting, that if thou shouldst fade -Thy memory will waste me to a shade:-- -For pity do not melt!"--"If I should stay," -Said Lamia, "here, upon this floor of clay, -And pain my steps upon these flowers too rough, -What canst thou say or do of charm enough -To dull the nice remembrance of my home? -Thou canst not ask me with thee here to roam -Over these hills and vales, where no joy is,-- -Empty of immortality and bliss! -Thou art a scholar, Lycius, and must know -That finer spirits cannot breathe below -In human climes, and live: Alas! poor youth, -What taste of purer air hast thou to soothe -My essence? What serener palaces, -Where I may all my many senses please, -And by mysterious sleights a hundred thirsts appease? -It cannot be--Adieu!" So said, she rose -Tiptoe with white arms spread. He, sick to lose -The amorous promise of her lone complain, -Swoon'd, murmuring of love, and pale with pain. -The cruel lady, without any show -Of sorrow for her tender favourite's woe, -But rather, if her eyes could brighter be, -With brighter eyes and slow amenity, -Put her new lips to his, and gave afresh -The life she had so tangled in her mesh: -And as he from one trance was wakening -Into another, she began to sing, -Happy in beauty, life, and love, and every thing, -A song of love, too sweet for earthly lyres, -While, like held breath, the stars drew in their panting -fires. -And then she whisper'd in such trembling tone, -As those who, safe together met alone -For the first time through many anguish'd days, -Use other speech than looks; bidding him raise -His drooping head, and clear his soul of doubt, -For that she was a woman, and without -Any more subtle fluid in her veins -Than throbbing blood, and that the self-same pains -Inhabited her frail-strung heart as his. -And next she wonder'd how his eyes could miss -Her face so long in Corinth, where, she said, -She dwelt but half retir'd, and there had led -Days happy as the gold coin could invent -Without the aid of love; yet in content -Till she saw him, as once she pass'd him by, -Where 'gainst a column he leant thoughtfully -At Venus' temple porch, 'mid baskets heap'd -Of amorous herbs and flowers, newly reap'd -Late on that eve, as 'twas the night before -The Adonian feast; whereof she saw no more, -But wept alone those days, for why should she adore? -Lycius from death awoke into amaze, -To see her still, and singing so sweet lays; -Then from amaze into delight he fell -To hear her whisper woman's lore so well; -And every word she spake entic'd him on -To unperplex'd delight and pleasure known. -Let the mad poets say whate'er they please -Of the sweets of Fairies, Peris, Goddesses, -There is not such a treat among them all, -Haunters of cavern, lake, and waterfall, -As a real woman, lineal indeed -From Pyrrha's pebbles or old Adam's seed. -Thus gentle Lamia judg'd, and judg'd aright, -That Lycius could not love in half a fright, -So threw the goddess off, and won his heart -More pleasantly by playing woman's part, -With no more awe than what her beauty gave, -That, while it smote, still guaranteed to save. -Lycius to all made eloquent reply, -Marrying to every word a twinborn sigh; -And last, pointing to Corinth, ask'd her sweet, -If 'twas too far that night for her soft feet. -The way was short, for Lamia's eagerness -Made, by a spell, the triple league decrease -To a few paces; not at all surmised -By blinded Lycius, so in her comprized. -They pass'd the city gates, he knew not how, -So noiseless, and he never thought to know. - -As men talk in a dream, so Corinth all, -Throughout her palaces imperial, -And all her populous streets and temples lewd, -Mutter'd, like tempest in the distance brew'd, -To the wide-spreaded night above her towers. -Men, women, rich and poor, in the cool hours, -Shuffled their sandals o'er the pavement white, -Companion'd or alone; while many a light -Flared, here and there, from wealthy festivals, -And threw their moving shadows on the walls, -Or found them cluster'd in the corniced shade -Of some arch'd temple door, or dusky colonnade. - -Muffling his face, of greeting friends in fear, -Her fingers he press'd hard, as one came near -With curl'd gray beard, sharp eyes, and smooth bald crown, -Slow-stepp'd, and robed in philosophic gown: -Lycius shrank closer, as they met and past, -Into his mantle, adding wings to haste, -While hurried Lamia trembled: "Ah," said he, -"Why do you shudder, love, so ruefully? -Why does your tender palm dissolve in dew?"-- -"I'm wearied," said fair Lamia: "tell me who -Is that old man? I cannot bring to mind -His features:--Lycius! wherefore did you blind -Yourself from his quick eyes?" Lycius replied, -"'Tis Apollonius sage, my trusty guide -And good instructor; but to-night he seems -The ghost of folly haunting my sweet dreams." - -While yet he spake they had arrived before -A pillar'd porch, with lofty portal door, -Where hung a silver lamp, whose phosphor glow -Reflected in the slabbed steps below, -Mild as a star in water; for so new, -And so unsullied was the marble hue, -So through the crystal polish, liquid fine, -Ran the dark veins, that none but feet divine -Could e'er have touch'd there. Sounds Æolian -Breath'd from the hinges, as the ample span -Of the wide doors disclos'd a place unknown -Some time to any, but those two alone, -And a few Persian mutes, who that same year -Were seen about the markets: none knew where -They could inhabit; the most curious -Were foil'd, who watch'd to trace them to their house: -And but the flitter-winged verse must tell, -For truth's sake, what woe afterwards befel, -'Twould humour many a heart to leave them thus, -Shut from the busy world of more incredulous. \ No newline at end of file +“As a daughter she no longer exists for me. Can’t you understand? +She simply doesn’t exist. Still, I cannot possibly leave her to the charity of strangers. I will arrange things so that she can live as she pleases, but I do not wish to hear of her. Who would ever have thought . . . the horror of it, the horror of it.” + +He shrugged his shoulders, shook his head, and raised his eyes. These words were spoken by Prince Michael Ivanovich to his brother Peter, who was governor of a province in Central Russia. Prince Peter was a man of fifty, Michael’s junior by ten years. + +On discovering that his daughter, who had left his house a year before, had settled here with her child, the elder brother had come from St. Petersburg to the provincial town, where the above conversation took place. + +Prince Michael Ivanovich was a tall, handsome, white-haired, fresh coloured man, proud and attractive in appearance and bearing. His family consisted of a vulgar, irritable wife, who wrangled with him continually over every petty detail, a son, a ne’er-do-well, spendthrift and roue–yet a + +“gentleman,” according to his father’s code, two daughters, of whom the elder had married well, and was living in St. Petersburg; and the younger, Lisa–his favourite, who had disappeared from home a year before. Only a short while ago he had found her with her child in this provincial town. + +Prince Peter wanted to ask his brother how, and under what circumstances, Lisa had left home, and who could possibly be the father of her child. +But he could not make up his mind to inquire. + +That very morning, when his wife had attempted to condole with her brother-in-law, +Prince Peter had observed a look of pain on his brother’s face. The look had at once been masked by an expression of unapproachable pride, and he had begun to question her about their flat, and the price she paid. At luncheon, before the family and guests, he had been witty and sarcastic as usual. Towards every one, excepting the children, whom he treated with almost reverent tenderness, he adopted an attitude of distant hauteur. And yet it was so natural to him that every one somehow acknowledged his right to be haughty. + +In the evening his brother arranged a game of whist. When he retired to the room which had been made ready for him, and was just beginning to take out his artificial teeth, some one tapped lightly on the door with two fingers. + +“Who is that?” + +“C’est moi, Michael.” + +Prince Michael Ivanovich recognised the voice of his sister-in-law, frowned, replaced his teeth, and said to himself, “What does she want?” Aloud he said, “Entrez.” + +His sister-in-law was a quiet, gentle creature, who bowed in submission to her husband’s will. But to many she seemed a crank, and some did not hesitate to call her a fool. She was pretty, but her hair was always carelessly dressed, and she herself was untidy and absent-minded. She had, also, the strangest, most unaristocratic ideas, by no means fitting in the wife of a high official. These ideas she would express most unexpectedly, to everybody’s astonishment, her husband’s no less than her friends’. + +“Fous pouvez me renvoyer, mais je ne m’en irai pas, je vous le dis d’avance,” she began, in her characteristic, indifferent way. + +“Dieu preserve,” answered her brother-in-law, with his usual somewhat exaggerated politeness, and brought forward a chair for her. + +“Ca ne vous derange pas?” she asked, taking out a cigarette. “I’m not going to say anything unpleasant, Michael. I only wanted to say something about Lisochka.” + +Michael Ivanovich sighed–the word pained him; but mastering + himself at once, he answered with a tired smile. “Our conversation can only + be on one subject, and that is the subject you wish to discuss.” He spoke without looking at her, and avoided even naming the subject. But his plump, pretty little sister-in-law was unabashed. She continued to regard him with the same gentle, imploring look in her blue eyes, sighing even more deeply. +“Michael, mon bon ami, have pity on her. She is only human.” + +“I never doubted that,” said Michael Ivanovich with a bitter smile. + +“She is your daughter.” + +“She was–but my dear Aline, why talk about this?” + +“Michael, dear, won’t you see her? I only wanted to say, that the one who is to blame–“ + +Prince Michael Ivanovich flushed; his face became cruel. + +“For heaven’s sake, let us stop. I have suffered enough. I have now but one desire, and that is to put her in such a position that she will be independent of others, and that she shall have no further need of communicating with me. Then she can live her own life, and my family and I need know nothing more about her. That is all I can do.” + +“Michael, you say nothing but ‘I’! She, too, is ‘I.'” + +“No doubt; but, dear Aline, please let us drop the matter. I feel it too deeply.” + +Alexandra Dmitrievna remained silent for a few moments, shaking her head. “And Masha, your wife, thinks as you do?” + +“Yes, quite.” + +Alexandra Dmitrievna made an inarticulate sound. + +“Brisons la dessus et bonne nuit,” said he. But she did not go. She stood silent a moment. Then,–“Peter tells me you intend to leave the money with the woman where she lives. Have you the address?” + +“I have.” + +“Don’t leave it with the woman, Michael! Go yourself. Just see how she lives. If you don’t want to see her, you need not. HE isn’t there; there is no one there.” + +Michael Ivanovich shuddered violently. + +“Why do you torture me so? It’s a sin against hospitality!” + +Alexandra Dmitrievna rose, and almost in tears, being touched by her own pleading, said, “She is so miserable, but she is such a dear.” + +He got up, and stood waiting for her to finish. She held out her hand. + +“Michael, you do wrong,” said she, and left him. + +For a long while after she had gone Michael Ivanovich walked to and fro on the square of carpet. He frowned and shivered, and exclaimed, “Oh, oh!” And then the sound of his own voice frightened him, and he was silent. + +His wounded pride tortured him. His daughter–his–brought up in the house of her mother, the famous Avdotia Borisovna, whom the Empress honoured with her visits, and acquaintance with whom was an honour for all the world! His daughter–; and he had lived his life as a knight of old, knowing neither fear nor blame. The fact that he had a natural son born of a Frenchwoman, whom he had settled abroad, did not lower his own self-esteem. And now this daughter, for whom he had not only done everything that a father could and should do; this daughter to whom he had given a splendid education and every opportunity to make a match in the best Russian society– this daughter to whom he had not only given all that a girl could desire, but whom he had really LOVED; whom he had admired, been proud of–this daughter had repaid him with such disgrace, that he was ashamed and could not face the eyes of men! + +He recalled the time when she was not merely his child, and a member of his family, but his darling, his joy and his pride. He saw her again, a little thing of eight or nine, bright, intelligent, lively, impetuous, graceful, with brilliant black eyes and flowing auburn hair. He remembered how she used to jump up on his knees and hug him, and tickle his neck; and how she would laugh, regardless of his protests, and continue to tickle him, and kiss his lips, his eyes, and his cheeks. He was naturally opposed to all demonstration, but this impetuous love moved him, and he often submitted to her petting. He remembered also how sweet it was to caress her. To remember all this, when that sweet child had become what she now was, a creature of whom he could not think without loathing. +He also recalled the time when she was growing into womanhood, and the curious feeling of fear and anger that he experienced when he became aware that men regarded her as a woman. He thought of his jealous love when she came coquettishly to him dressed for a ball, and knowing that she was pretty. He dreaded the passionate glances which fell upon her, that she not only did not understand but rejoiced in. “Yes,” thought he, “that superstition of woman’s purity! Quite the contrary, they do not know shame–they lack this sense.” He remembered how, quite inexplicably to him, she had refused two very good suitors. She had become more and more fascinated by her own success in the round of gaieties she lived in. + +But this success could not last long. A year passed, then two, then three. She was a familiar figure, beautiful–but her first youth had passed, and she had become somehow part of the ball-room furniture. Michael Ivanovich remembered how he had realised that she was on the road to spinsterhood, and desired but one thing for her. He must get her married off as quickly as possible, perhaps not quite so well as might have been arranged earlier, but still a respectable match. + +But it seemed to him she had behaved with a pride that bordered on insolence. Remembering this, his anger rose more and more fiercely against her. To think of her refusing so many decent men, only to end in this disgrace. “Oh, oh!” he groaned again. + +Then stopping, he lit a cigarette, and tried to think of other things. He would send her money, without ever letting her see him. But memories came again. He remembered–it was not so very long ago, for she was more than twenty then–her beginning a flirtation with a boy of fourteen, a cadet of the Corps of Pages who had been staying with them in the country. She had driven the boy half crazy; he had wept in his distraction. Then how she had rebuked her father severely, coldly, and even rudely, when, to put an end to this stupid affair, he had sent the boy away. She seemed somehow to consider herself insulted. Since then father and daughter had drifted into undisguised hostility. + +“I was right,” he said to himself. “She is a wicked and shameless woman.” + +And then, as a last ghastly memory, there was the letter from Moscow, in which she wrote that she could not return home; that she was a miserable, abandoned woman, asking only to be forgiven and forgotten. Then the horrid recollection of the scene with his wife came to him; their surmises and their suspicions, which became a certainty. The calamity had happened in Finland, where they had let her visit her aunt; and the culprit was an insignificant Swede, a student, an empty-headed, worthless creature–and married. + +All this came back to him now as he paced backwards and forwards on the bedroom carpet, recollecting his former love for her, his pride in her. He recoiled with terror before the incomprehensible fact of her downfall, and he hated her for the agony she was causing him. He remembered the conversation with his sister-in-law, and tried to imagine how he might forgive her. But as soon as the thought of “him” arose, there surged up in his heart horror, disgust, and wounded pride. He groaned aloud, and tried to think of something else. + +“No, it is impossible; I will hand over the money to Peter to give her monthly. And as for me, I have no longer a daughter.” + +And again a curious feeling overpowered him: a mixture of self-pity at the recollection of his love for her, and of fury against her for causing him this anguish. + +II + +DURING the last year Lisa had without doubt lived through more than in all the preceding twenty-five. Suddenly she had realised the emptiness of her whole life. It rose before her, base and sordid– this life at home and among the rich set in St. Petersburg– this animal existence that never sounded the depths, but only touched the shallows of life. +It was well enough for a year or two, or perhaps even three. But when it went on for seven or eight years, with its parties, balls, concerts, and suppers; with its costumes and coiffures to display the charms of the body; with its adorers old and young, all alike seemingly possessed of some unaccountable right to have everything, to laugh at everything; and with its summer months spent in the same way, everything yielding but a superficial pleasure, even music and reading merely touching upon life’s problems, but never solving them–all this holding out no promise of change, and losing its charm more and more–she began to despair. She had desperate moods when she longed to die. + +Her friends directed her thoughts to charity. On the one hand, she saw poverty which was real and repulsive, and a sham poverty even more repulsive and pitiable; on the other, she saw the terrible indifference of the lady patronesses who came in carriages and gowns worth thousands. Life became to her more and more unbearable. She yearned for something real, for life itself–not this playing at living, not this skimming life of its cream. Of real life there was none. The best of her memories was her love for the little cadet Koko. That had been a good, honest, straight-forward impulse, and now there was nothing like it. There could not be. She grew more and more depressed, and in this gloomy mood she went to visit an aunt in Finland. The fresh scenery and surroundings, the people strangely different to her own, appealed to her at any rate as a new experience. + +How and when it all began she could not clearly remember. Her aunt had another guest, a Swede. He talked of his work, his people, the latest Swedish novel. Somehow, she herself did not know how that terrible fascination of glances and smiles began, the meaning of which cannot be put into words. + +These smiles and glances seemed to reveal to each, not only the soul of the other, but some vital and universal mystery. Every word they spoke was invested by these smiles with a profound and wonderful significance. Music, too, when they were listening together, or when they sang duets, became full of the same deep meaning. So, also, the words in the books they read aloud. Sometimes they would argue, but the moment their eyes met, or a smile flashed between them, the discussion remained far behind. They soared beyond it to some higher plane consecrated to themselves. + +How it had come about, how and when the devil, who had seized hold of them both, first appeared behind these smiles and glances, she could not say. But, when terror first seized her, the invisible threads that bound them were already so interwoven that she had no power to tear herself free. She could only count on him and on his honour. She hoped that he would not make use of his power; yet all the while she vaguely desired it. + +Her weakness was the greater, because she had nothing to support her in the struggle. She was weary of society life and she had no affection for her mother. Her father, so she thought, had cast her away from him, and she longed passionately to live and to have done with play. Love, the perfect love of a woman for a man, held the promise of life for her. Her strong, passionate nature, too, was dragging her thither. In the tall, strong figure of this man, with his fair hair and light upturned moustache, under which shone a smile attractive and compelling, she saw the promise of that life for which she longed. And then the smiles and glances, the hope of something so incredibly beautiful, led, as they were bound to lead, to that which she feared but unconsciously awaited. +Suddenly all that was beautiful, joyous, spiritual, and full of promise for the future, became animal and sordid, sad and despairing. + +She looked into his eyes and tried to smile, pretending that she feared nothing, that everything was as it should be; but deep down in her soul she knew it was all over. She understood that she had not found in him what she had sought; that which she had once known in herself and in Koko. She told him that he must write to her father asking her hand in marriage. This he promised to do; but when she met him next he said it was impossible for him to write just then. She saw something vague and furtive in his eyes, and her distrust of him grew. The following day he wrote to her, telling her that he was already married, though his wife had left him long since; that he knew she would despise him for the wrong he had done her, and implored her forgiveness. She made him come to see her. She said she loved him; that she felt herself bound to him for ever whether he was married or not, and would never leave him. The next time they met he told her that he and his parents were so poor that he could only offer her the meanest existence. She answered that she needed nothing, and was ready to go with him at once wherever he wished. He endeavoured to dissuade her, advising her to wait; and so she waited. But to live on with this secret, with occasional meetings, and merely corresponding with him, all hidden from her family, was agonising, and she insisted again that he must take her away. At first, when she returned to St. Petersburg, be wrote promising to come, and then letters ceased and she knew no more of him. + +She tried to lead her old life, but it was impossible. She fell ill, and the efforts of the doctors were unavailing; in her hopelessness she resolved to kill herself. But how was she to do this, so that her death might seem natural? She really desired to take her life, and imagined that she had irrevocably decided on the step. So, obtaining some poison, she poured it into a glass, and in another instant would have drunk it, had not her sister’s little son of five at that very moment run in to show her a toy his grandmother had given him. She caressed the child, and, suddenly stopping short, burst into tears. + +The thought overpowered her that she, too, might have been a mother had he not been married, and this vision of motherhood made her look into her own soul for the first time. She began to think not of what others would say of her, but of her own life. To kill oneself because of what the world might say was easy; but the moment she saw her own life dissociated from the world, to take that life was out of the question. She threw away the poison, and ceased to think of suicide. + +Then her life within began. It was real life, and despite the torture of it, had the possibility been given her, she would not have turned back from it. She began to pray, but there was no comfort in prayer; and her suffering was less for herself than for her father, whose grief she foresaw and understood. + +Thus months dragged along, and then something happened which entirely transformed her life. One day, when she was at work upon a quilt, she suddenly experienced a strange sensation. No–it seemed impossible. Motionless she sat with her work in hand. Was it possible that this was IT. Forgetting everything, his baseness and deceit, her mother’s querulousness, and her father’s sorrow, she smiled. She shuddered at the recollection that she was on the point of killing it, together with herself. +She now directed all her thoughts to getting away–somewhere where she could bear her child–and become a miserable, pitiful mother, but a mother withal. Somehow she planned and arranged it all, leaving her home and settling in a distant provincial town, where no one could find her, and where she thought she would be far from her people. But, unfortunately, her father’s brother received an appointment there, a thing she could not possibly foresee. For four months she had been living in the house of a midwife– one Maria Ivanovna; and, on learning that her uncle had come to the town, she was preparing to fly to a still remoter hiding-place. + +III + +MICHAEL IVANOVICH awoke early next morning. He entered his brother’s study, and handed him the cheque, filled in for a sum which he asked him to pay in monthly instalments to his daughter. He inquired when the express left for St. Petersburg. The train left at seven in the evening, giving him time for an early dinner before leaving. He breakfasted with his sister-in-law, who refrained from mentioning the subject which was so painful to him, but only looked at him timidly; and after breakfast he went out for his regular morning walk. + +Alexandra Dmitrievna followed him into the hall. + +“Go into the public gardens, Michael–it is very charming there, and quite near to Everything,” said she, meeting his sombre looks with a pathetic glance. + +Michael Ivanovich followed her advice and went to the public gardens, which were so near to Everything, and meditated with annoyance on the stupidity, the obstinacy, and heartlessness of women. + +“She is not in the very least sorry for me,” he thought of his sister-in-law. “She cannot even understand my sorrow. And what of her?” He was thinking of his daughter. “She knows what all this means to me–the torture. What a blow in one’s old age! My days will be shortened by it! But I’d rather have it over than endure this agony. And all that ‘pour les beaux yeux d’un chenapan’–oh!” he moaned; and a wave of hatred and fury arose in him as he thought of what would be said in the town when every one knew. (And no doubt every one knew already.) Such a feeling of rage possessed him that he would have liked to beat it into her head, and make her understand what she had done. These women never understand. “It is quite near Everything,” suddenly came to his mind, and getting out his notebook, he found her address. Vera Ivanovna Silvestrova, Kukonskaya Street, Abromov’s house. She was living under this name. He left the gardens and called a cab. + +“Whom do you wish to see, sir?” asked the midwife, Maria Ivanovna, when he stepped on the narrow landing +of the steep, stuffy staircase. + +“Does Madame Silvestrova live here?” + +“Vera Ivanovna? Yes; please come in. She has gone out; she’s gone to the shop round the corner. + But she’ll be back in a minute.” + +Michael Ivanovich followed the stout figure of Maria Ivanovna into a tiny parlour, and from the next room came the screams of a baby, sounding cross and peevish, which filled him with disgust. They cut him like a knife. + +Maria Ivanovna apologised, and went into the room, and he could hear her soothing the child. The child became quiet, and she returned. + +“That is her baby; she’ll be back in a minute. You are a friend of hers, I suppose?” + +“Yes–a friend–but I think I had better come back later on,” said Michael Ivanovich, preparing to go. It was too unbearable, this preparation to meet her, and any explanation seemed impossible. + +He had just turned to leave, when he heard quick, light steps on the stairs, and he recognised Lisa’s voice. + +“Maria Ivanovna–has he been crying while I’ve been gone–I was–“ + +Then she saw her father. The parcel she was carrying fell from her hands. +“Father!” she cried, and stopped in the doorway, white and trembling. + +He remained motionless, staring at her. She had grown so thin. Her eyes were larger, her nose sharper, her hands worn and bony. He neither knew what to do, nor what to say. He forgot all his grief about his dishonour. He only felt sorrow, infinite sorrow for her; sorrow for her thinness, and for her miserable rough clothing; and most of all, for her pitiful face and imploring eyes. + +“Father–forgive,” she said, moving towards him. + +“Forgive–forgive me,” he murmured; and he began to sob like a child, kissing her face and hands, and wetting them with his tears. + +In his pity for her he understood himself. And when he saw himself as he was, + + he realised how he had wronged her, how guilty he had been in his pride, in his coldness, even in his anger towards her. He was glad that it was he who was guilty, and that he had nothing to forgive, but that he himself needed forgiveness. She took him to her tiny room, and told him how she lived; but she did not show him the child, nor did she mention the past, knowing how painful it would be to him. + +He told her that she must live differently. + +“Yes; if I could only live in the country,” said she. + +“We will talk it over,” he said. Suddenly the child began to wail and to scream. She opened her eyes very wide; and, not taking them from her father’s face, remained hesitating and motionless. + + +“Well–I suppose you must feed him,” said Michael Ivanovich, and frowned with the obvious effort. + +She got up, and suddenly the wild idea seized her to show him whom she loved so deeply the thing she now loved best of all in the world. But first she looked at her father’s face. Would he be angry or not? His face revealed no anger, only suffering. + +“Yes, go, go,” said he; “God bless you. Yes. I’ll come again to-morrow, and we will decide. Good-bye, my darling– good-bye.” Again he found it hard to swallow the lump in his throat. + +When Michael Ivanovich returned to his brother’s house, Alexandra Dmitrievna immediately rushed to him. + +“Well?” + +“Well? Nothing.” + +“Have you seen?” she asked, guessing from his expression that something had happened. + +“Yes,” he answered shortly, and began to cry. “I’m getting old and stupid,” said he, mastering his emotion. + +“No; you are growing wise–very wise.” \ No newline at end of file diff --git a/src/LowercaseSentenceTokenizer.java b/src/LowercaseSentenceTokenizer.java index cc8285d..d40796c 100644 --- a/src/LowercaseSentenceTokenizer.java +++ b/src/LowercaseSentenceTokenizer.java @@ -1,3 +1,6 @@ + + + import java.util.ArrayList; import java.util.List; import java.util.Scanner; @@ -28,9 +31,40 @@ public class LowercaseSentenceTokenizer implements Tokenizer { * @param scanner the Scanner to read the input text from * @return a list of tokens, where each token is a word or a period */ - public List tokenize(Scanner scanner) { - // TODO: Implement this function to convert the scanner's input to a list of words and periods - return null; - } + /* TODO: Implement this function to convert the scanner's input to a list of words and periods + return null; */ + + +@Override + public List tokenize(Scanner scanner) { + List tokens = new ArrayList<>(); + + String input = scanner.nextLine().toLowerCase(); + + // Use "\\s+" to split by any number of spaces (removes empty tokens) + String[] words = input.split("\\s+"); + + for (String word : words) { + if (word.endsWith(".")) { + // I ues the substring in this website https://www.w3schools.com/jsref/jsref_substring.asp + /* explain what this code do + This code reads a sentence, converts it to lowercase, and splits it into words. It then checks +if any word ends with a period (.). If there is a period at the end of a word, the period is +separated and stored as its own token. Anything without a period gets directly added to the list. Finally, +This function separates the words from the period as different tokens in a list. + */ + String withoutPeriod = word.substring(0, word.length() - 1); + if (!withoutPeriod.isEmpty()) { + tokens.add(withoutPeriod); // Add the word without the period + } + tokens.add("."); // Add the period as a separate token + } else { + tokens.add(word); + } + } + + return tokens; + } } + diff --git a/src/LowercaseSentenceTokenizerTest.java b/src/LowercaseSentenceTokenizerTest.java index 85ac3a2..3e4231c 100644 --- a/src/LowercaseSentenceTokenizerTest.java +++ b/src/LowercaseSentenceTokenizerTest.java @@ -20,6 +20,16 @@ void testTokenizeWithNoCapitalizationOrPeriod() { * Write your test here! */ +@Test +void testTokenizeWithExtraSpaces() { + LowercaseSentenceTokenizer tokenizer = new LowercaseSentenceTokenizer(); + Scanner scanner = new Scanner("hello hi hi hi hello hello"); + List tokens = tokenizer.tokenize(scanner); + + assertEquals(List.of("hello", "hi", "hi", "hi", "hello", "hello"), tokens); +} + + // Wave 3 @Test From 3938e2247331f4a53eb03d04fc543c8f85444375 Mon Sep 17 00:00:00 2001 From: elena5100 <194572363+elena5100@users.noreply.github.com> Date: Thu, 30 Jan 2025 00:12:39 -0800 Subject: [PATCH 3/4] Updated UnigramWordPredictor and test files, added training text --- keatsTraining.txt | 602 +++++++++++++++++++--------- src/LowercaseSentenceTokenizer.java | 2 +- src/UnigramWordPredictor.java | 71 ++-- src/UnigramWordPredictorTest.java | 160 +++----- src/WordPredictor.java | 2 +- 5 files changed, 500 insertions(+), 337 deletions(-) diff --git a/keatsTraining.txt b/keatsTraining.txt index fb0db76..8a15084 100644 --- a/keatsTraining.txt +++ b/keatsTraining.txt @@ -1,195 +1,407 @@ -“As a daughter she no longer exists for me. Can’t you understand? -She simply doesn’t exist. Still, I cannot possibly leave her to the charity of strangers. I will arrange things so that she can live as she pleases, but I do not wish to hear of her. Who would ever have thought . . . the horror of it, the horror of it.” - -He shrugged his shoulders, shook his head, and raised his eyes. These words were spoken by Prince Michael Ivanovich to his brother Peter, who was governor of a province in Central Russia. Prince Peter was a man of fifty, Michael’s junior by ten years. - -On discovering that his daughter, who had left his house a year before, had settled here with her child, the elder brother had come from St. Petersburg to the provincial town, where the above conversation took place. - -Prince Michael Ivanovich was a tall, handsome, white-haired, fresh coloured man, proud and attractive in appearance and bearing. His family consisted of a vulgar, irritable wife, who wrangled with him continually over every petty detail, a son, a ne’er-do-well, spendthrift and roue–yet a - -“gentleman,” according to his father’s code, two daughters, of whom the elder had married well, and was living in St. Petersburg; and the younger, Lisa–his favourite, who had disappeared from home a year before. Only a short while ago he had found her with her child in this provincial town. - -Prince Peter wanted to ask his brother how, and under what circumstances, Lisa had left home, and who could possibly be the father of her child. -But he could not make up his mind to inquire. - -That very morning, when his wife had attempted to condole with her brother-in-law, -Prince Peter had observed a look of pain on his brother’s face. The look had at once been masked by an expression of unapproachable pride, and he had begun to question her about their flat, and the price she paid. At luncheon, before the family and guests, he had been witty and sarcastic as usual. Towards every one, excepting the children, whom he treated with almost reverent tenderness, he adopted an attitude of distant hauteur. And yet it was so natural to him that every one somehow acknowledged his right to be haughty. - -In the evening his brother arranged a game of whist. When he retired to the room which had been made ready for him, and was just beginning to take out his artificial teeth, some one tapped lightly on the door with two fingers. - -“Who is that?” - -“C’est moi, Michael.” - -Prince Michael Ivanovich recognised the voice of his sister-in-law, frowned, replaced his teeth, and said to himself, “What does she want?” Aloud he said, “Entrez.” - -His sister-in-law was a quiet, gentle creature, who bowed in submission to her husband’s will. But to many she seemed a crank, and some did not hesitate to call her a fool. She was pretty, but her hair was always carelessly dressed, and she herself was untidy and absent-minded. She had, also, the strangest, most unaristocratic ideas, by no means fitting in the wife of a high official. These ideas she would express most unexpectedly, to everybody’s astonishment, her husband’s no less than her friends’. - -“Fous pouvez me renvoyer, mais je ne m’en irai pas, je vous le dis d’avance,” she began, in her characteristic, indifferent way. - -“Dieu preserve,” answered her brother-in-law, with his usual somewhat exaggerated politeness, and brought forward a chair for her. - -“Ca ne vous derange pas?” she asked, taking out a cigarette. “I’m not going to say anything unpleasant, Michael. I only wanted to say something about Lisochka.” - -Michael Ivanovich sighed–the word pained him; but mastering - himself at once, he answered with a tired smile. “Our conversation can only - be on one subject, and that is the subject you wish to discuss.” He spoke without looking at her, and avoided even naming the subject. But his plump, pretty little sister-in-law was unabashed. She continued to regard him with the same gentle, imploring look in her blue eyes, sighing even more deeply. -“Michael, mon bon ami, have pity on her. She is only human.” - -“I never doubted that,” said Michael Ivanovich with a bitter smile. - -“She is your daughter.” - -“She was–but my dear Aline, why talk about this?” - -“Michael, dear, won’t you see her? I only wanted to say, that the one who is to blame–“ - -Prince Michael Ivanovich flushed; his face became cruel. - -“For heaven’s sake, let us stop. I have suffered enough. I have now but one desire, and that is to put her in such a position that she will be independent of others, and that she shall have no further need of communicating with me. Then she can live her own life, and my family and I need know nothing more about her. That is all I can do.” - -“Michael, you say nothing but ‘I’! She, too, is ‘I.'” - -“No doubt; but, dear Aline, please let us drop the matter. I feel it too deeply.” - -Alexandra Dmitrievna remained silent for a few moments, shaking her head. “And Masha, your wife, thinks as you do?” - -“Yes, quite.” - -Alexandra Dmitrievna made an inarticulate sound. - -“Brisons la dessus et bonne nuit,” said he. But she did not go. She stood silent a moment. Then,–“Peter tells me you intend to leave the money with the woman where she lives. Have you the address?” - -“I have.” - -“Don’t leave it with the woman, Michael! Go yourself. Just see how she lives. If you don’t want to see her, you need not. HE isn’t there; there is no one there.” - -Michael Ivanovich shuddered violently. - -“Why do you torture me so? It’s a sin against hospitality!” - -Alexandra Dmitrievna rose, and almost in tears, being touched by her own pleading, said, “She is so miserable, but she is such a dear.” - -He got up, and stood waiting for her to finish. She held out her hand. - -“Michael, you do wrong,” said she, and left him. - -For a long while after she had gone Michael Ivanovich walked to and fro on the square of carpet. He frowned and shivered, and exclaimed, “Oh, oh!” And then the sound of his own voice frightened him, and he was silent. - -His wounded pride tortured him. His daughter–his–brought up in the house of her mother, the famous Avdotia Borisovna, whom the Empress honoured with her visits, and acquaintance with whom was an honour for all the world! His daughter–; and he had lived his life as a knight of old, knowing neither fear nor blame. The fact that he had a natural son born of a Frenchwoman, whom he had settled abroad, did not lower his own self-esteem. And now this daughter, for whom he had not only done everything that a father could and should do; this daughter to whom he had given a splendid education and every opportunity to make a match in the best Russian society– this daughter to whom he had not only given all that a girl could desire, but whom he had really LOVED; whom he had admired, been proud of–this daughter had repaid him with such disgrace, that he was ashamed and could not face the eyes of men! - -He recalled the time when she was not merely his child, and a member of his family, but his darling, his joy and his pride. He saw her again, a little thing of eight or nine, bright, intelligent, lively, impetuous, graceful, with brilliant black eyes and flowing auburn hair. He remembered how she used to jump up on his knees and hug him, and tickle his neck; and how she would laugh, regardless of his protests, and continue to tickle him, and kiss his lips, his eyes, and his cheeks. He was naturally opposed to all demonstration, but this impetuous love moved him, and he often submitted to her petting. He remembered also how sweet it was to caress her. To remember all this, when that sweet child had become what she now was, a creature of whom he could not think without loathing. -He also recalled the time when she was growing into womanhood, and the curious feeling of fear and anger that he experienced when he became aware that men regarded her as a woman. He thought of his jealous love when she came coquettishly to him dressed for a ball, and knowing that she was pretty. He dreaded the passionate glances which fell upon her, that she not only did not understand but rejoiced in. “Yes,” thought he, “that superstition of woman’s purity! Quite the contrary, they do not know shame–they lack this sense.” He remembered how, quite inexplicably to him, she had refused two very good suitors. She had become more and more fascinated by her own success in the round of gaieties she lived in. - -But this success could not last long. A year passed, then two, then three. She was a familiar figure, beautiful–but her first youth had passed, and she had become somehow part of the ball-room furniture. Michael Ivanovich remembered how he had realised that she was on the road to spinsterhood, and desired but one thing for her. He must get her married off as quickly as possible, perhaps not quite so well as might have been arranged earlier, but still a respectable match. - -But it seemed to him she had behaved with a pride that bordered on insolence. Remembering this, his anger rose more and more fiercely against her. To think of her refusing so many decent men, only to end in this disgrace. “Oh, oh!” he groaned again. - -Then stopping, he lit a cigarette, and tried to think of other things. He would send her money, without ever letting her see him. But memories came again. He remembered–it was not so very long ago, for she was more than twenty then–her beginning a flirtation with a boy of fourteen, a cadet of the Corps of Pages who had been staying with them in the country. She had driven the boy half crazy; he had wept in his distraction. Then how she had rebuked her father severely, coldly, and even rudely, when, to put an end to this stupid affair, he had sent the boy away. She seemed somehow to consider herself insulted. Since then father and daughter had drifted into undisguised hostility. - -“I was right,” he said to himself. “She is a wicked and shameless woman.” - -And then, as a last ghastly memory, there was the letter from Moscow, in which she wrote that she could not return home; that she was a miserable, abandoned woman, asking only to be forgiven and forgotten. Then the horrid recollection of the scene with his wife came to him; their surmises and their suspicions, which became a certainty. The calamity had happened in Finland, where they had let her visit her aunt; and the culprit was an insignificant Swede, a student, an empty-headed, worthless creature–and married. - -All this came back to him now as he paced backwards and forwards on the bedroom carpet, recollecting his former love for her, his pride in her. He recoiled with terror before the incomprehensible fact of her downfall, and he hated her for the agony she was causing him. He remembered the conversation with his sister-in-law, and tried to imagine how he might forgive her. But as soon as the thought of “him” arose, there surged up in his heart horror, disgust, and wounded pride. He groaned aloud, and tried to think of something else. - -“No, it is impossible; I will hand over the money to Peter to give her monthly. And as for me, I have no longer a daughter.” - -And again a curious feeling overpowered him: a mixture of self-pity at the recollection of his love for her, and of fury against her for causing him this anguish. - -II - -DURING the last year Lisa had without doubt lived through more than in all the preceding twenty-five. Suddenly she had realised the emptiness of her whole life. It rose before her, base and sordid– this life at home and among the rich set in St. Petersburg– this animal existence that never sounded the depths, but only touched the shallows of life. -It was well enough for a year or two, or perhaps even three. But when it went on for seven or eight years, with its parties, balls, concerts, and suppers; with its costumes and coiffures to display the charms of the body; with its adorers old and young, all alike seemingly possessed of some unaccountable right to have everything, to laugh at everything; and with its summer months spent in the same way, everything yielding but a superficial pleasure, even music and reading merely touching upon life’s problems, but never solving them–all this holding out no promise of change, and losing its charm more and more–she began to despair. She had desperate moods when she longed to die. - -Her friends directed her thoughts to charity. On the one hand, she saw poverty which was real and repulsive, and a sham poverty even more repulsive and pitiable; on the other, she saw the terrible indifference of the lady patronesses who came in carriages and gowns worth thousands. Life became to her more and more unbearable. She yearned for something real, for life itself–not this playing at living, not this skimming life of its cream. Of real life there was none. The best of her memories was her love for the little cadet Koko. That had been a good, honest, straight-forward impulse, and now there was nothing like it. There could not be. She grew more and more depressed, and in this gloomy mood she went to visit an aunt in Finland. The fresh scenery and surroundings, the people strangely different to her own, appealed to her at any rate as a new experience. - -How and when it all began she could not clearly remember. Her aunt had another guest, a Swede. He talked of his work, his people, the latest Swedish novel. Somehow, she herself did not know how that terrible fascination of glances and smiles began, the meaning of which cannot be put into words. - -These smiles and glances seemed to reveal to each, not only the soul of the other, but some vital and universal mystery. Every word they spoke was invested by these smiles with a profound and wonderful significance. Music, too, when they were listening together, or when they sang duets, became full of the same deep meaning. So, also, the words in the books they read aloud. Sometimes they would argue, but the moment their eyes met, or a smile flashed between them, the discussion remained far behind. They soared beyond it to some higher plane consecrated to themselves. - -How it had come about, how and when the devil, who had seized hold of them both, first appeared behind these smiles and glances, she could not say. But, when terror first seized her, the invisible threads that bound them were already so interwoven that she had no power to tear herself free. She could only count on him and on his honour. She hoped that he would not make use of his power; yet all the while she vaguely desired it. - -Her weakness was the greater, because she had nothing to support her in the struggle. She was weary of society life and she had no affection for her mother. Her father, so she thought, had cast her away from him, and she longed passionately to live and to have done with play. Love, the perfect love of a woman for a man, held the promise of life for her. Her strong, passionate nature, too, was dragging her thither. In the tall, strong figure of this man, with his fair hair and light upturned moustache, under which shone a smile attractive and compelling, she saw the promise of that life for which she longed. And then the smiles and glances, the hope of something so incredibly beautiful, led, as they were bound to lead, to that which she feared but unconsciously awaited. -Suddenly all that was beautiful, joyous, spiritual, and full of promise for the future, became animal and sordid, sad and despairing. - -She looked into his eyes and tried to smile, pretending that she feared nothing, that everything was as it should be; but deep down in her soul she knew it was all over. She understood that she had not found in him what she had sought; that which she had once known in herself and in Koko. She told him that he must write to her father asking her hand in marriage. This he promised to do; but when she met him next he said it was impossible for him to write just then. She saw something vague and furtive in his eyes, and her distrust of him grew. The following day he wrote to her, telling her that he was already married, though his wife had left him long since; that he knew she would despise him for the wrong he had done her, and implored her forgiveness. She made him come to see her. She said she loved him; that she felt herself bound to him for ever whether he was married or not, and would never leave him. The next time they met he told her that he and his parents were so poor that he could only offer her the meanest existence. She answered that she needed nothing, and was ready to go with him at once wherever he wished. He endeavoured to dissuade her, advising her to wait; and so she waited. But to live on with this secret, with occasional meetings, and merely corresponding with him, all hidden from her family, was agonising, and she insisted again that he must take her away. At first, when she returned to St. Petersburg, be wrote promising to come, and then letters ceased and she knew no more of him. - -She tried to lead her old life, but it was impossible. She fell ill, and the efforts of the doctors were unavailing; in her hopelessness she resolved to kill herself. But how was she to do this, so that her death might seem natural? She really desired to take her life, and imagined that she had irrevocably decided on the step. So, obtaining some poison, she poured it into a glass, and in another instant would have drunk it, had not her sister’s little son of five at that very moment run in to show her a toy his grandmother had given him. She caressed the child, and, suddenly stopping short, burst into tears. - -The thought overpowered her that she, too, might have been a mother had he not been married, and this vision of motherhood made her look into her own soul for the first time. She began to think not of what others would say of her, but of her own life. To kill oneself because of what the world might say was easy; but the moment she saw her own life dissociated from the world, to take that life was out of the question. She threw away the poison, and ceased to think of suicide. - -Then her life within began. It was real life, and despite the torture of it, had the possibility been given her, she would not have turned back from it. She began to pray, but there was no comfort in prayer; and her suffering was less for herself than for her father, whose grief she foresaw and understood. - -Thus months dragged along, and then something happened which entirely transformed her life. One day, when she was at work upon a quilt, she suddenly experienced a strange sensation. No–it seemed impossible. Motionless she sat with her work in hand. Was it possible that this was IT. Forgetting everything, his baseness and deceit, her mother’s querulousness, and her father’s sorrow, she smiled. She shuddered at the recollection that she was on the point of killing it, together with herself. -She now directed all her thoughts to getting away–somewhere where she could bear her child–and become a miserable, pitiful mother, but a mother withal. Somehow she planned and arranged it all, leaving her home and settling in a distant provincial town, where no one could find her, and where she thought she would be far from her people. But, unfortunately, her father’s brother received an appointment there, a thing she could not possibly foresee. For four months she had been living in the house of a midwife– one Maria Ivanovna; and, on learning that her uncle had come to the town, she was preparing to fly to a still remoter hiding-place. - -III - -MICHAEL IVANOVICH awoke early next morning. He entered his brother’s study, and handed him the cheque, filled in for a sum which he asked him to pay in monthly instalments to his daughter. He inquired when the express left for St. Petersburg. The train left at seven in the evening, giving him time for an early dinner before leaving. He breakfasted with his sister-in-law, who refrained from mentioning the subject which was so painful to him, but only looked at him timidly; and after breakfast he went out for his regular morning walk. - -Alexandra Dmitrievna followed him into the hall. - -“Go into the public gardens, Michael–it is very charming there, and quite near to Everything,” said she, meeting his sombre looks with a pathetic glance. - -Michael Ivanovich followed her advice and went to the public gardens, which were so near to Everything, and meditated with annoyance on the stupidity, the obstinacy, and heartlessness of women. - -“She is not in the very least sorry for me,” he thought of his sister-in-law. “She cannot even understand my sorrow. And what of her?” He was thinking of his daughter. “She knows what all this means to me–the torture. What a blow in one’s old age! My days will be shortened by it! But I’d rather have it over than endure this agony. And all that ‘pour les beaux yeux d’un chenapan’–oh!” he moaned; and a wave of hatred and fury arose in him as he thought of what would be said in the town when every one knew. (And no doubt every one knew already.) Such a feeling of rage possessed him that he would have liked to beat it into her head, and make her understand what she had done. These women never understand. “It is quite near Everything,” suddenly came to his mind, and getting out his notebook, he found her address. Vera Ivanovna Silvestrova, Kukonskaya Street, Abromov’s house. She was living under this name. He left the gardens and called a cab. - -“Whom do you wish to see, sir?” asked the midwife, Maria Ivanovna, when he stepped on the narrow landing -of the steep, stuffy staircase. - -“Does Madame Silvestrova live here?” - -“Vera Ivanovna? Yes; please come in. She has gone out; she’s gone to the shop round the corner. - But she’ll be back in a minute.” - -Michael Ivanovich followed the stout figure of Maria Ivanovna into a tiny parlour, and from the next room came the screams of a baby, sounding cross and peevish, which filled him with disgust. They cut him like a knife. - -Maria Ivanovna apologised, and went into the room, and he could hear her soothing the child. The child became quiet, and she returned. - -“That is her baby; she’ll be back in a minute. You are a friend of hers, I suppose?” - -“Yes–a friend–but I think I had better come back later on,” said Michael Ivanovich, preparing to go. It was too unbearable, this preparation to meet her, and any explanation seemed impossible. - -He had just turned to leave, when he heard quick, light steps on the stairs, and he recognised Lisa’s voice. - -“Maria Ivanovna–has he been crying while I’ve been gone–I was–“ - -Then she saw her father. The parcel she was carrying fell from her hands. -“Father!” she cried, and stopped in the doorway, white and trembling. - -He remained motionless, staring at her. She had grown so thin. Her eyes were larger, her nose sharper, her hands worn and bony. He neither knew what to do, nor what to say. He forgot all his grief about his dishonour. He only felt sorrow, infinite sorrow for her; sorrow for her thinness, and for her miserable rough clothing; and most of all, for her pitiful face and imploring eyes. - -“Father–forgive,” she said, moving towards him. - -“Forgive–forgive me,” he murmured; and he began to sob like a child, kissing her face and hands, and wetting them with his tears. - -In his pity for her he understood himself. And when he saw himself as he was, - - he realised how he had wronged her, how guilty he had been in his pride, in his coldness, even in his anger towards her. He was glad that it was he who was guilty, and that he had nothing to forgive, but that he himself needed forgiveness. She took him to her tiny room, and told him how she lived; but she did not show him the child, nor did she mention the past, knowing how painful it would be to him. - -He told her that she must live differently. - -“Yes; if I could only live in the country,” said she. - -“We will talk it over,” he said. Suddenly the child began to wail and to scream. She opened her eyes very wide; and, not taking them from her father’s face, remained hesitating and motionless. - - -“Well–I suppose you must feed him,” said Michael Ivanovich, and frowned with the obvious effort. - -She got up, and suddenly the wild idea seized her to show him whom she loved so deeply the thing she now loved best of all in the world. But first she looked at her father’s face. Would he be angry or not? His face revealed no anger, only suffering. - -“Yes, go, go,” said he; “God bless you. Yes. I’ll come again to-morrow, and we will decide. Good-bye, my darling– good-bye.” Again he found it hard to swallow the lump in his throat. - -When Michael Ivanovich returned to his brother’s house, Alexandra Dmitrievna immediately rushed to him. - -“Well?” - -“Well? Nothing.” - -“Have you seen?” she asked, guessing from his expression that something had happened. - -“Yes,” he answered shortly, and began to cry. “I’m getting old and stupid,” said he, mastering his emotion. - -“No; you are growing wise–very wise.” \ No newline at end of file +Upon a time, before the faery broods +Drove Nymph and Satyr from the prosperous woods, +Before King Oberon's bright diadem, +Sceptre, and mantle, clasp'd with dewy gem, +Frighted away the Dryads and the Fauns +From rushes green, and brakes, and cowslip'd lawns, +The ever-smitten Hermes empty left +His golden throne, bent warm on amorous theft: +From high Olympus had he stolen light, +On this side of Jove's clouds, to escape the sight +Of his great summoner, and made retreat +Into a forest on the shores of Crete. +For somewhere in that sacred island dwelt +A nymph, to whom all hoofed Satyrs knelt; +At whose white feet the languid Tritons poured +Pearls, while on land they wither'd and adored. +Fast by the springs where she to bathe was wont, +And in those meads where sometime she might haunt, +Were strewn rich gifts, unknown to any Muse, +Though Fancy's casket were unlock'd to choose. +Ah, what a world of love was at her feet! +So Hermes thought, and a celestial heat +Burnt from his winged heels to either ear, +That from a whiteness, as the lily clear, +Blush'd into roses 'mid his golden hair, +Fallen in jealous curls about his shoulders bare. +From vale to vale, from wood to wood, he flew, +Breathing upon the flowers his passion new, +And wound with many a river to its head, +To find where this sweet nymph prepar'd her secret bed: +In vain; the sweet nymph might nowhere be found, +And so he rested, on the lonely ground, +Pensive, and full of painful jealousies +Of the Wood-Gods, and even the very trees. +There as he stood, he heard a mournful voice, +Such as once heard, in gentle heart, destroys +All pain but pity: thus the lone voice spake: +"When from this wreathed tomb shall I awake! +When move in a sweet body fit for life, +And love, and pleasure, and the ruddy strife +Of hearts and lips! Ah, miserable me!" +The God, dove-footed, glided silently +Round bush and tree, soft-brushing, in his speed, +The taller grasses and full-flowering weed, +Until he found a palpitating snake, +Bright, and cirque-couchant in a dusky brake. + +She was a gordian shape of dazzling hue, +Vermilion-spotted, golden, green, and blue; +Striped like a zebra, freckled like a pard, +Eyed like a peacock, and all crimson barr'd; +And full of silver moons, that, as she breathed, +Dissolv'd, or brighter shone, or interwreathed +Their lustres with the gloomier tapestries-- +So rainbow-sided, touch'd with miseries, +She seem'd, at once, some penanced lady elf, +Some demon's mistress, or the demon's self. +Upon her crest she wore a wannish fire +Sprinkled with stars, like Ariadne's tiar: +Her head was serpent, but ah, bitter-sweet! +She had a woman's mouth with all its pearls complete: +And for her eyes: what could such eyes do there +But weep, and weep, that they were born so fair? +As Proserpine still weeps for her Sicilian air. +Her throat was serpent, but the words she spake +Came, as through bubbling honey, for Love's sake, +And thus; while Hermes on his pinions lay, +Like a stoop'd falcon ere he takes his prey. + +"Fair Hermes, crown'd with feathers, fluttering light, +I had a splendid dream of thee last night: +I saw thee sitting, on a throne of gold, +Among the Gods, upon Olympus old, +The only sad one; for thou didst not hear +The soft, lute-finger'd Muses chaunting clear, +Nor even Apollo when he sang alone, +Deaf to his throbbing throat's long, long melodious moan. +I dreamt I saw thee, robed in purple flakes, +Break amorous through the clouds, as morning breaks, +And, swiftly as a bright Phoebean dart, +Strike for the Cretan isle; and here thou art! +Too gentle Hermes, hast thou found the maid?" +Whereat the star of Lethe not delay'd +His rosy eloquence, and thus inquired: +"Thou smooth-lipp'd serpent, surely high inspired! +Thou beauteous wreath, with melancholy eyes, +Possess whatever bliss thou canst devise, +Telling me only where my nymph is fled,-- +Where she doth breathe!" "Bright planet, thou hast said," +Return'd the snake, "but seal with oaths, fair God!" +"I swear," said Hermes, "by my serpent rod, +And by thine eyes, and by thy starry crown!" +Light flew his earnest words, among the blossoms blown. +Then thus again the brilliance feminine: +"Too frail of heart! for this lost nymph of thine, +Free as the air, invisibly, she strays +About these thornless wilds; her pleasant days +She tastes unseen; unseen her nimble feet +Leave traces in the grass and flowers sweet; +From weary tendrils, and bow'd branches green, +She plucks the fruit unseen, she bathes unseen: +And by my power is her beauty veil'd +To keep it unaffronted, unassail'd +By the love-glances of unlovely eyes, +Of Satyrs, Fauns, and blear'd Silenus' sighs. +Pale grew her immortality, for woe +Of all these lovers, and she grieved so +I took compassion on her, bade her steep +Her hair in weird syrops, that would keep +Her loveliness invisible, yet free +To wander as she loves, in liberty. +Thou shalt behold her, Hermes, thou alone, +If thou wilt, as thou swearest, grant my boon!" +Then, once again, the charmed God began +An oath, and through the serpent's ears it ran +Warm, tremulous, devout, psalterian. +Ravish'd, she lifted her Circean head, +Blush'd a live damask, and swift-lisping said, +"I was a woman, let me have once more +A woman's shape, and charming as before. +I love a youth of Corinth--O the bliss! +Give me my woman's form, and place me where he is. +Stoop, Hermes, let me breathe upon thy brow, +And thou shalt see thy sweet nymph even now." +The God on half-shut feathers sank serene, +She breath'd upon his eyes, and swift was seen +Of both the guarded nymph near-smiling on the green. +It was no dream; or say a dream it was, +Real are the dreams of Gods, and smoothly pass +Their pleasures in a long immortal dream. +One warm, flush'd moment, hovering, it might seem +Dash'd by the wood-nymph's beauty, so he burn'd; +Then, lighting on the printless verdure, turn'd +To the swoon'd serpent, and with languid arm, +Delicate, put to proof the lythe Caducean charm. +So done, upon the nymph his eyes he bent +Full of adoring tears and blandishment, +And towards her stept: she, like a moon in wane, +Faded before him, cower'd, nor could restrain +Her fearful sobs, self-folding like a flower +That faints into itself at evening hour: +But the God fostering her chilled hand, +She felt the warmth, her eyelids open'd bland, +And, like new flowers at morning song of bees, +Bloom'd, and gave up her honey to the lees. +Into the green-recessed woods they flew; +Nor grew they pale, as mortal lovers do. + +Left to herself, the serpent now began +To change; her elfin blood in madness ran, +Her mouth foam'd, and the grass, therewith besprent, +Wither'd at dew so sweet and virulent; +Her eyes in torture fix'd, and anguish drear, +Hot, glaz'd, and wide, with lid-lashes all sear, +Flash'd phosphor and sharp sparks, without one cooling tear. +The colours all inflam'd throughout her train, +She writh'd about, convuls'd with scarlet pain: +A deep volcanian yellow took the place +Of all her milder-mooned body's grace; +And, as the lava ravishes the mead, +Spoilt all her silver mail, and golden brede; +Made gloom of all her frecklings, streaks and bars, +Eclips'd her crescents, and lick'd up her stars: +So that, in moments few, she was undrest +Of all her sapphires, greens, and amethyst, +And rubious-argent: of all these bereft, +Nothing but pain and ugliness were left. +Still shone her crown; that vanish'd, also she +Melted and disappear'd as suddenly; +And in the air, her new voice luting soft, +Cried, "Lycius! gentle Lycius!"--Borne aloft +With the bright mists about the mountains hoar +These words dissolv'd: Crete's forests heard no more. + +Whither fled Lamia, now a lady bright, +A full-born beauty new and exquisite? +She fled into that valley they pass o'er +Who go to Corinth from Cenchreas' shore; +And rested at the foot of those wild hills, +The rugged founts of the Peræan rills, +And of that other ridge whose barren back +Stretches, with all its mist and cloudy rack, +South-westward to Cleone. There she stood +About a young bird's flutter from a wood, +Fair, on a sloping green of mossy tread, +By a clear pool, wherein she passioned +To see herself escap'd from so sore ills, +While her robes flaunted with the daffodils. + +Ah, happy Lycius!--for she was a maid +More beautiful than ever twisted braid, +Or sigh'd, or blush'd, or on spring-flowered lea +Spread a green kirtle to the minstrelsy: +A virgin purest lipp'd, yet in the lore +Of love deep learned to the red heart's core: +Not one hour old, yet of sciential brain +To unperplex bliss from its neighbour pain; +Define their pettish limits, and estrange +Their points of contact, and swift counterchange; +Intrigue with the specious chaos, and dispart +Its most ambiguous atoms with sure art; +As though in Cupid's college she had spent +Sweet days a lovely graduate, still unshent, +And kept his rosy terms in idle languishment. + +Why this fair creature chose so fairily +By the wayside to linger, we shall see; +But first 'tis fit to tell how she could muse +And dream, when in the serpent prison-house, +Of all she list, strange or magnificent: +How, ever, where she will'd, her spirit went; +Whether to faint Elysium, or where +Down through tress-lifting waves the Nereids fair +Wind into Thetis' bower by many a pearly stair; +Or where God Bacchus drains his cups divine, +Stretch'd out, at ease, beneath a glutinous pine; +Or where in Pluto's gardens palatine +Mulciber's columns gleam in far piazzian line. +And sometimes into cities she would send +Her dream, with feast and rioting to blend; +And once, while among mortals dreaming thus, +She saw the young Corinthian Lycius +Charioting foremost in the envious race, +Like a young Jove with calm uneager face, +And fell into a swooning love of him. +Now on the moth-time of that evening dim +He would return that way, as well she knew, +To Corinth from the shore; for freshly blew +The eastern soft wind, and his galley now +Grated the quaystones with her brazen prow +In port Cenchreas, from Egina isle +Fresh anchor'd; whither he had been awhile +To sacrifice to Jove, whose temple there +Waits with high marble doors for blood and incense rare. +Jove heard his vows, and better'd his desire; +For by some freakful chance he made retire +From his companions, and set forth to walk, +Perhaps grown wearied of their Corinth talk: +Over the solitary hills he fared, +Thoughtless at first, but ere eve's star appeared +His phantasy was lost, where reason fades, +In the calm'd twilight of Platonic shades. +Lamia beheld him coming, near, more near-- +Close to her passing, in indifference drear, +His silent sandals swept the mossy green; +So neighbour'd to him, and yet so unseen +She stood: he pass'd, shut up in mysteries, +His mind wrapp'd like his mantle, while her eyes +Follow'd his steps, and her neck regal white +Turn'd--syllabling thus, "Ah, Lycius bright, +And will you leave me on the hills alone? +Lycius, look back! and be some pity shown." +He did; not with cold wonder fearingly, +But Orpheus-like at an Eurydice; +For so delicious were the words she sung, +It seem'd he had lov'd them a whole summer long: +And soon his eyes had drunk her beauty up, +Leaving no drop in the bewildering cup, +And still the cup was full,--while he, afraid +Lest she should vanish ere his lip had paid +Due adoration, thus began to adore; +Her soft look growing coy, she saw his chain so sure: +"Leave thee alone! Look back! Ah, Goddess, see +Whether my eyes can ever turn from thee! +For pity do not this sad heart belie-- +Even as thou vanishest so I shall die. +Stay! though a Naiad of the rivers, stay! +To thy far wishes will thy streams obey: +Stay! though the greenest woods be thy domain, +Alone they can drink up the morning rain: +Though a descended Pleiad, will not one +Of thine harmonious sisters keep in tune +Thy spheres, and as thy silver proxy shine? +So sweetly to these ravish'd ears of mine +Came thy sweet greeting, that if thou shouldst fade +Thy memory will waste me to a shade:-- +For pity do not melt!"--"If I should stay," +Said Lamia, "here, upon this floor of clay, +And pain my steps upon these flowers too rough, +What canst thou say or do of charm enough +To dull the nice remembrance of my home? +Thou canst not ask me with thee here to roam +Over these hills and vales, where no joy is,-- +Empty of immortality and bliss! +Thou art a scholar, Lycius, and must know +That finer spirits cannot breathe below +In human climes, and live: Alas! poor youth, +What taste of purer air hast thou to soothe +My essence? What serener palaces, +Where I may all my many senses please, +And by mysterious sleights a hundred thirsts appease? +It cannot be--Adieu!" So said, she rose +Tiptoe with white arms spread. He, sick to lose +The amorous promise of her lone complain, +Swoon'd, murmuring of love, and pale with pain. +The cruel lady, without any show +Of sorrow for her tender favourite's woe, +But rather, if her eyes could brighter be, +With brighter eyes and slow amenity, +Put her new lips to his, and gave afresh +The life she had so tangled in her mesh: +And as he from one trance was wakening +Into another, she began to sing, +Happy in beauty, life, and love, and every thing, +A song of love, too sweet for earthly lyres, +While, like held breath, the stars drew in their panting +fires. +And then she whisper'd in such trembling tone, +As those who, safe together met alone +For the first time through many anguish'd days, +Use other speech than looks; bidding him raise +His drooping head, and clear his soul of doubt, +For that she was a woman, and without +Any more subtle fluid in her veins +Than throbbing blood, and that the self-same pains +Inhabited her frail-strung heart as his. +And next she wonder'd how his eyes could miss +Her face so long in Corinth, where, she said, +She dwelt but half retir'd, and there had led +Days happy as the gold coin could invent +Without the aid of love; yet in content +Till she saw him, as once she pass'd him by, +Where 'gainst a column he leant thoughtfully +At Venus' temple porch, 'mid baskets heap'd +Of amorous herbs and flowers, newly reap'd +Late on that eve, as 'twas the night before +The Adonian feast; whereof she saw no more, +But wept alone those days, for why should she adore? +Lycius from death awoke into amaze, +To see her still, and singing so sweet lays; +Then from amaze into delight he fell +To hear her whisper woman's lore so well; +And every word she spake entic'd him on +To unperplex'd delight and pleasure known. +Let the mad poets say whate'er they please +Of the sweets of Fairies, Peris, Goddesses, +There is not such a treat among them all, +Haunters of cavern, lake, and waterfall, +As a real woman, lineal indeed +From Pyrrha's pebbles or old Adam's seed. +Thus gentle Lamia judg'd, and judg'd aright, +That Lycius could not love in half a fright, +So threw the goddess off, and won his heart +More pleasantly by playing woman's part, +With no more awe than what her beauty gave, +That, while it smote, still guaranteed to save. +Lycius to all made eloquent reply, +Marrying to every word a twinborn sigh; +And last, pointing to Corinth, ask'd her sweet, +If 'twas too far that night for her soft feet. +The way was short, for Lamia's eagerness +Made, by a spell, the triple league decrease +To a few paces; not at all surmised +By blinded Lycius, so in her comprized. +They pass'd the city gates, he knew not how, +So noiseless, and he never thought to know. + +As men talk in a dream, so Corinth all, +Throughout her palaces imperial, +And all her populous streets and temples lewd, +Mutter'd, like tempest in the distance brew'd, +To the wide-spreaded night above her towers. +Men, women, rich and poor, in the cool hours, +Shuffled their sandals o'er the pavement white, +Companion'd or alone; while many a light +Flared, here and there, from wealthy festivals, +And threw their moving shadows on the walls, +Or found them cluster'd in the corniced shade +Of some arch'd temple door, or dusky colonnade. + +Muffling his face, of greeting friends in fear, +Her fingers he press'd hard, as one came near +With curl'd gray beard, sharp eyes, and smooth bald crown, +Slow-stepp'd, and robed in philosophic gown: +Lycius shrank closer, as they met and past, +Into his mantle, adding wings to haste, +While hurried Lamia trembled: "Ah," said he, +"Why do you shudder, love, so ruefully? +Why does your tender palm dissolve in dew?"-- +"I'm wearied," said fair Lamia: "tell me who +Is that old man? I cannot bring to mind +His features:--Lycius! wherefore did you blind +Yourself from his quick eyes?" Lycius replied, +"'Tis Apollonius sage, my trusty guide +And good instructor; but to-night he seems +The ghost of folly haunting my sweet dreams." + +While yet he spake they had arrived before +A pillar'd porch, with lofty portal door, +Where hung a silver lamp, whose phosphor glow +Reflected in the slabbed steps below, +Mild as a star in water; for so new, +And so unsullied was the marble hue, +So through the crystal polish, liquid fine, +Ran the dark veins, that none but feet divine +Could e'er have touch'd there. Sounds Æolian +Breath'd from the hinges, as the ample span +Of the wide doors disclos'd a place unknown +Some time to any, but those two alone, +And a few Persian mutes, who that same year +Were seen about the markets: none knew where +They could inhabit; the most curious +Were foil'd, who watch'd to trace them to their house: +And but the flitter-winged verse must tell, +For truth's sake, what woe afterwards befel, +'Twould humour many a heart to leave them thus, +Shut from the busy world of more incredulous. \ No newline at end of file diff --git a/src/LowercaseSentenceTokenizer.java b/src/LowercaseSentenceTokenizer.java index d40796c..d95bbf5 100644 --- a/src/LowercaseSentenceTokenizer.java +++ b/src/LowercaseSentenceTokenizer.java @@ -47,7 +47,7 @@ public List tokenize(Scanner scanner) { for (String word : words) { if (word.endsWith(".")) { // I ues the substring in this website https://www.w3schools.com/jsref/jsref_substring.asp - /* explain what this code do + /* explain what this code do... This code reads a sentence, converts it to lowercase, and splits it into words. It then checks if any word ends with a period (.). If there is a period at the end of a word, the period is separated and stored as its own token. Anything without a period gets directly added to the list. Finally, diff --git a/src/UnigramWordPredictor.java b/src/UnigramWordPredictor.java index d713250..b014b36 100644 --- a/src/UnigramWordPredictor.java +++ b/src/UnigramWordPredictor.java @@ -2,6 +2,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Random; import java.util.Scanner; /** @@ -10,8 +11,9 @@ * words that directly follow it in the text. */ public class UnigramWordPredictor implements WordPredictor { - private Map> neighborMap; + private Map> neighborMap; private Tokenizer tokenizer; + private Random random; /** * Constructs a UnigramWordPredictor with the specified tokenizer. @@ -20,6 +22,8 @@ public class UnigramWordPredictor implements WordPredictor { */ public UnigramWordPredictor(Tokenizer tokenizer) { this.tokenizer = tokenizer; + this.neighborMap = new HashMap<>(); + this.random = new Random(); } /** @@ -29,29 +33,27 @@ public UnigramWordPredictor(Tokenizer tokenizer) { * in the text. The resultant map is stored in the neighborMap * instance variable. * - * For example: - * If the input text is: "The cat sat. The cat slept. The dog barked." - * After tokenizing, the tokens would be: ["the", "cat", "sat", ".", "the", "cat", "slept", ".", "the", "dog", "barked", "."] - * - * The resulting map (neighborMap) would be: - * { - * "the" -> ["cat", "cat", "dog"], - * "cat" -> ["sat", "slept"], - * "sat" -> ["."], - * "." -> ["the", "the"], - * "slept" -> ["."], - * "dog" -> ["barked"], - * "barked" -> ["."] - * } - * - * The order of the map and the order of each list is not important. - * * @param scanner the Scanner to read the training text from */ public void train(Scanner scanner) { List trainingWords = tokenizer.tokenize(scanner); - // TODO: Convert the trainingWords into neighborMap here + if (trainingWords.isEmpty()) { + return; + } + + for (int i = 0; i < trainingWords.size() - 1; i++) { + String currentWord = trainingWords.get(i); + String nextWord = trainingWords.get(i + 1); + + // this code mean ...if currentWord is not already in neighborMap, add it with an empty list as its value. + + + neighborMap.putIfAbsent(currentWord, new ArrayList<>()); + + // Store the word that follows + neighborMap.get(currentWord).add(nextWord); + } } /** @@ -98,18 +100,37 @@ public void train(Scanner scanner) { * @param context a list of words representing the current context * @return the predicted next word, or null if no prediction can be made */ + + /* explain the code what do ..The predictNextWord method takes a list of + words as context and predicts the next word. It first checks if the context is empty and + returns null if so. Then, it retrieves the last word from the list and looks it up in neighborMap, + which stores words and their possible next words from training data. If the last word exists in the map + and has a list of next words, it randomly selects one based on frequency. If no match is found, it returns + null. + */ +/* I ues this link to learn on this https://stackoverflow.com/questions/4672806/java-simplest-way-to-get-last-word-in-a-string */ public String predictNextWord(List context) { - // TODO: Return a predicted word given the words preceding it - // Hint: only the last word in context should be looked at - return null; + if (context.isEmpty()) { + return null; + } + + String lastWord = context.get(context.size() - 1); // Get last word + + if (neighborMap.containsKey(lastWord)) { + List nextWords = neighborMap.get(lastWord); + + if (!nextWords.isEmpty()) { + return nextWords.get(random.nextInt(nextWords.size())); + } + } + + return null; } - + /** * Returns a copy of the neighbor map. The neighbor map is a mapping * from each word to a list of words that have followed it in the training data. * - * You do not need to modify this method for your project. - * * @return a copy of the neighbor map */ public Map> getNeighborMap() { diff --git a/src/UnigramWordPredictorTest.java b/src/UnigramWordPredictorTest.java index 08618a3..ca6a6f9 100644 --- a/src/UnigramWordPredictorTest.java +++ b/src/UnigramWordPredictorTest.java @@ -6,41 +6,27 @@ class UnigramWordPredictorTest { - // Wave 4 - /** - * Tests the train method by checking that the generated neighbor map matches the expected map. - * - * The training data simulates the tokens: - * "the cat sat. the cat slept. the dog barked." - * - * This results in the following sequences: - * - "the" is followed by "cat", then "cat", and finally "dog". - * - "cat" is followed by "sat" and then "slept". - * - "barked", "sat", and "slept" are both followed by a period ("."). - * - "dog" is followed by "barked". - * - is followed by a period ("."). - * - "." is followed by the word "the" twice. - * - * The expected neighbor map is checked to see if it matches this pattern. - * The test does not care about the order of the map or the lists. - */ + // Wave 4 - Testing the train method @Test void testTrainAndGetNeighborMap() { - // Use a fake tokenizer with predefined tokens + // Simulated training text with tokenized words FakeTokenizer fakeTokenizer = new FakeTokenizer( List.of("the", "cat", "sat", ".", "the", "cat", "slept", ".", "the", "dog", "barked", ".") ); + + // Create predictor and train it UnigramWordPredictor predictor = new UnigramWordPredictor(fakeTokenizer); - - predictor.train(null); // The scanner input is ignored by FakeTokenizer + predictor.train(null); // Scanner input is ignored by FakeTokenizer + + // Get the generated neighbor map Map> neighborMap = predictor.getNeighborMap(); - // Sort the actual lists to ensure order does not affect comparison + // Sort lists inside the map for easy comparison for (List values : neighborMap.values()) { - values.sort(null); // Sort alphabetically + values.sort(null); } - // Pre-sorted expected map + // Expected word mappings based on training text Map> expectedMap = Map.of( "the", List.of("cat", "cat", "dog"), "cat", List.of("sat", "slept"), @@ -51,131 +37,75 @@ void testTrainAndGetNeighborMap() { "barked", List.of(".") ); + // Check if our model created the correct word map assertEquals(expectedMap, neighborMap); } - // Wave 5 - /** - * Tests the predictNextWord method using a different example to verify that the correct word - * is predicted based on the training data. - * - * The training data simulates the tokens: - * "the quick brown fox. a quick red fox. the slow green turtle." - * - * This results in the following patterns: - * - "the" is followed by "quick" and "slow". - * - "a" is followed by "quick". - * - "quick" is followed by "brown" and "red". - * - "fox" is followed by a period "." twice. - * - "slow" is followed by "green". - * - "green" is followed by "turtle". - * - "turtle" is followed by a period ".". - * - A period "." is followed by "the" twice and "a" once. - * - * The test verifies that the predictions for various words are consistent with these patterns. - */ + // Wave 5 - Testing predictNextWord() @Test void testPredictNextWord() { - // Use a fake tokenizer with a new set of predefined tokens + // Simulated tokenized words for testing predictions FakeTokenizer fakeTokenizer = new FakeTokenizer( List.of("the", "quick", "brown", "fox", ".", "a", "quick", "red", "fox", ".", "the", "slow", "green", "turtle", ".") ); + + // Create and train predictor UnigramWordPredictor predictor = new UnigramWordPredictor(fakeTokenizer); - - predictor.train(null); // The scanner input is ignored by FakeTokenizer - - // Predicting the next word after "the" should be "quick" or "slow" - String nextWord = predictor.predictNextWord(List.of("the")); - assertTrue(nextWord.equals("quick") || nextWord.equals("slow")); - - // Predicting the next word after "a" should be "quick" - nextWord = predictor.predictNextWord(List.of("a")); - assertEquals("quick", nextWord); - - // Predicting the next word after "quick" should be either "brown" or "red" - nextWord = predictor.predictNextWord(List.of("quick")); - assertTrue(nextWord.equals("brown") || nextWord.equals("red")); - - // Predicting the next word after "fox" should always be "." - nextWord = predictor.predictNextWord(List.of("fox")); - assertEquals(".", nextWord); - - // Predicting the next word after "slow" should always be "green" - nextWord = predictor.predictNextWord(List.of("slow")); - assertEquals("green", nextWord); - - // Predicting the next word after "turtle" should always be "." - nextWord = predictor.predictNextWord(List.of("turtle")); - assertEquals(".", nextWord); - - // Predicting the next word after "." should be "the" or "a" - nextWord = predictor.predictNextWord(List.of(".")); - assertTrue(nextWord.equals("the") || nextWord.equals("a")); - } + predictor.train(null); + // Check word predictions based on training + assertTrue(List.of("quick", "slow").contains(predictor.predictNextWord(List.of("the")))); + assertEquals("quick", predictor.predictNextWord(List.of("a"))); + assertTrue(List.of("brown", "red").contains(predictor.predictNextWord(List.of("quick")))); + assertEquals(".", predictor.predictNextWord(List.of("fox"))); + assertEquals("green", predictor.predictNextWord(List.of("slow"))); + assertEquals(".", predictor.predictNextWord(List.of("turtle"))); + assertTrue(List.of("the", "a").contains(predictor.predictNextWord(List.of(".")))); + } - // Wave 5 - /** - * Tests the predictNextWord method probabilistically by performing multiple trials to check if - * the predicted words appear with the expected frequencies. - * - * The training data simulates the tokens: - * "the cat sat. the cat slept. the dog barked." - * - * Expected probabilities based on the training data: - * - "the" is followed by "cat" twice and "dog" once, so "cat" should appear 2/3 of the time, - * and "dog" should appear 1/3 of the time. - * - "cat" is followed by "sat" and "slept", so each should appear 50% of the time. - * - "dog" is always followed by "barked". - * - Each period is always followed by "the". - * - * The test runs multiple trials to estimate these probabilities and compares them to the - * expected values with some tolerance for variation. - */ + // Wave 5 - Probabilistic test for predictNextWord() @Test void testPredictNextWordProbabilistically() { - // Use a fake tokenizer with predefined tokens + // Training data FakeTokenizer fakeTokenizer = new FakeTokenizer( List.of("the", "cat", "sat", ".", "the", "cat", "slept", ".", "the", "dog", "barked", ".") ); + UnigramWordPredictor predictor = new UnigramWordPredictor(fakeTokenizer); - - predictor.train(null); // The scanner input is ignored by FakeTokenizer + predictor.train(null); - // Perform multiple trials to check word frequencies - int trials = 10000; // Number of trials for statistical testing - double tolerance = 0.05; // Tolerance for frequency comparison + // Number of trials for probability check + int trials = 10000; + double tolerance = 0.05; // Allow 5% deviation - // Expected probabilities - Map> expectedProbabilities = new HashMap<>(); - expectedProbabilities.put("the", Map.of("cat", 2.0 / 3.0, "dog", 1.0 / 3.0)); - expectedProbabilities.put("cat", Map.of("sat", 0.5, "slept", 0.5)); - expectedProbabilities.put("dog", Map.of("barked", 1.0)); - expectedProbabilities.put(".", Map.of("the", 1.0)); + // Expected probabilities based on word frequency + Map> expectedProbabilities = Map.of( + "the", Map.of("cat", 2.0 / 3.0, "dog", 1.0 / 3.0), + "cat", Map.of("sat", 0.5, "slept", 0.5), + "dog", Map.of("barked", 1.0), + ".", Map.of("the", 1.0) + ); - // Run trials for each test case + // Check predictions for each word for (String word : expectedProbabilities.keySet()) { Map counts = new HashMap<>(); Map expected = expectedProbabilities.get(word); - // Initialize counts for expected words - for (String nextWord : expected.keySet()) { - counts.put(nextWord, 0); - } + // Initialize word count + expected.keySet().forEach(nextWord -> counts.put(nextWord, 0)); - // Perform trials + // Run trials to collect frequency data for (int i = 0; i < trials; i++) { String predictedWord = predictor.predictNextWord(List.of(word)); counts.put(predictedWord, counts.getOrDefault(predictedWord, 0) + 1); } - // Check frequencies + // Compare observed vs expected probability for (String nextWord : expected.keySet()) { double observedFrequency = counts.get(nextWord) / (double) trials; double expectedFrequency = expected.get(nextWord); assertTrue(Math.abs(observedFrequency - expectedFrequency) < tolerance, - "Observed frequency of '" + nextWord + "' after '" + word + - "' was " + observedFrequency + ", expected " + expectedFrequency); + "Frequency mismatch for '" + word + "': observed " + observedFrequency + ", expected " + expectedFrequency); } } } diff --git a/src/WordPredictor.java b/src/WordPredictor.java index 6b00478..b6b12e3 100644 --- a/src/WordPredictor.java +++ b/src/WordPredictor.java @@ -23,4 +23,4 @@ public interface WordPredictor { * @return the predicted next word, or null if no prediction can be made */ public String predictNextWord(List context); -} +} \ No newline at end of file From 0de3514b51d2852ed7a0dc1f096294440e1c20c3 Mon Sep 17 00:00:00 2001 From: elena5100 <194572363+elena5100@users.noreply.github.com> Date: Thu, 30 Jan 2025 00:31:05 -0800 Subject: [PATCH 4/4] fixing my work --- oscarWildeTraining.txt | 195 ++++++++++++++++++++++++++++++ src/UnigramWordPredictorTest.java | 81 ++++++++++--- 2 files changed, 257 insertions(+), 19 deletions(-) create mode 100644 oscarWildeTraining.txt diff --git a/oscarWildeTraining.txt b/oscarWildeTraining.txt new file mode 100644 index 0000000..fb0db76 --- /dev/null +++ b/oscarWildeTraining.txt @@ -0,0 +1,195 @@ +“As a daughter she no longer exists for me. Can’t you understand? +She simply doesn’t exist. Still, I cannot possibly leave her to the charity of strangers. I will arrange things so that she can live as she pleases, but I do not wish to hear of her. Who would ever have thought . . . the horror of it, the horror of it.” + +He shrugged his shoulders, shook his head, and raised his eyes. These words were spoken by Prince Michael Ivanovich to his brother Peter, who was governor of a province in Central Russia. Prince Peter was a man of fifty, Michael’s junior by ten years. + +On discovering that his daughter, who had left his house a year before, had settled here with her child, the elder brother had come from St. Petersburg to the provincial town, where the above conversation took place. + +Prince Michael Ivanovich was a tall, handsome, white-haired, fresh coloured man, proud and attractive in appearance and bearing. His family consisted of a vulgar, irritable wife, who wrangled with him continually over every petty detail, a son, a ne’er-do-well, spendthrift and roue–yet a + +“gentleman,” according to his father’s code, two daughters, of whom the elder had married well, and was living in St. Petersburg; and the younger, Lisa–his favourite, who had disappeared from home a year before. Only a short while ago he had found her with her child in this provincial town. + +Prince Peter wanted to ask his brother how, and under what circumstances, Lisa had left home, and who could possibly be the father of her child. +But he could not make up his mind to inquire. + +That very morning, when his wife had attempted to condole with her brother-in-law, +Prince Peter had observed a look of pain on his brother’s face. The look had at once been masked by an expression of unapproachable pride, and he had begun to question her about their flat, and the price she paid. At luncheon, before the family and guests, he had been witty and sarcastic as usual. Towards every one, excepting the children, whom he treated with almost reverent tenderness, he adopted an attitude of distant hauteur. And yet it was so natural to him that every one somehow acknowledged his right to be haughty. + +In the evening his brother arranged a game of whist. When he retired to the room which had been made ready for him, and was just beginning to take out his artificial teeth, some one tapped lightly on the door with two fingers. + +“Who is that?” + +“C’est moi, Michael.” + +Prince Michael Ivanovich recognised the voice of his sister-in-law, frowned, replaced his teeth, and said to himself, “What does she want?” Aloud he said, “Entrez.” + +His sister-in-law was a quiet, gentle creature, who bowed in submission to her husband’s will. But to many she seemed a crank, and some did not hesitate to call her a fool. She was pretty, but her hair was always carelessly dressed, and she herself was untidy and absent-minded. She had, also, the strangest, most unaristocratic ideas, by no means fitting in the wife of a high official. These ideas she would express most unexpectedly, to everybody’s astonishment, her husband’s no less than her friends’. + +“Fous pouvez me renvoyer, mais je ne m’en irai pas, je vous le dis d’avance,” she began, in her characteristic, indifferent way. + +“Dieu preserve,” answered her brother-in-law, with his usual somewhat exaggerated politeness, and brought forward a chair for her. + +“Ca ne vous derange pas?” she asked, taking out a cigarette. “I’m not going to say anything unpleasant, Michael. I only wanted to say something about Lisochka.” + +Michael Ivanovich sighed–the word pained him; but mastering + himself at once, he answered with a tired smile. “Our conversation can only + be on one subject, and that is the subject you wish to discuss.” He spoke without looking at her, and avoided even naming the subject. But his plump, pretty little sister-in-law was unabashed. She continued to regard him with the same gentle, imploring look in her blue eyes, sighing even more deeply. +“Michael, mon bon ami, have pity on her. She is only human.” + +“I never doubted that,” said Michael Ivanovich with a bitter smile. + +“She is your daughter.” + +“She was–but my dear Aline, why talk about this?” + +“Michael, dear, won’t you see her? I only wanted to say, that the one who is to blame–“ + +Prince Michael Ivanovich flushed; his face became cruel. + +“For heaven’s sake, let us stop. I have suffered enough. I have now but one desire, and that is to put her in such a position that she will be independent of others, and that she shall have no further need of communicating with me. Then she can live her own life, and my family and I need know nothing more about her. That is all I can do.” + +“Michael, you say nothing but ‘I’! She, too, is ‘I.'” + +“No doubt; but, dear Aline, please let us drop the matter. I feel it too deeply.” + +Alexandra Dmitrievna remained silent for a few moments, shaking her head. “And Masha, your wife, thinks as you do?” + +“Yes, quite.” + +Alexandra Dmitrievna made an inarticulate sound. + +“Brisons la dessus et bonne nuit,” said he. But she did not go. She stood silent a moment. Then,–“Peter tells me you intend to leave the money with the woman where she lives. Have you the address?” + +“I have.” + +“Don’t leave it with the woman, Michael! Go yourself. Just see how she lives. If you don’t want to see her, you need not. HE isn’t there; there is no one there.” + +Michael Ivanovich shuddered violently. + +“Why do you torture me so? It’s a sin against hospitality!” + +Alexandra Dmitrievna rose, and almost in tears, being touched by her own pleading, said, “She is so miserable, but she is such a dear.” + +He got up, and stood waiting for her to finish. She held out her hand. + +“Michael, you do wrong,” said she, and left him. + +For a long while after she had gone Michael Ivanovich walked to and fro on the square of carpet. He frowned and shivered, and exclaimed, “Oh, oh!” And then the sound of his own voice frightened him, and he was silent. + +His wounded pride tortured him. His daughter–his–brought up in the house of her mother, the famous Avdotia Borisovna, whom the Empress honoured with her visits, and acquaintance with whom was an honour for all the world! His daughter–; and he had lived his life as a knight of old, knowing neither fear nor blame. The fact that he had a natural son born of a Frenchwoman, whom he had settled abroad, did not lower his own self-esteem. And now this daughter, for whom he had not only done everything that a father could and should do; this daughter to whom he had given a splendid education and every opportunity to make a match in the best Russian society– this daughter to whom he had not only given all that a girl could desire, but whom he had really LOVED; whom he had admired, been proud of–this daughter had repaid him with such disgrace, that he was ashamed and could not face the eyes of men! + +He recalled the time when she was not merely his child, and a member of his family, but his darling, his joy and his pride. He saw her again, a little thing of eight or nine, bright, intelligent, lively, impetuous, graceful, with brilliant black eyes and flowing auburn hair. He remembered how she used to jump up on his knees and hug him, and tickle his neck; and how she would laugh, regardless of his protests, and continue to tickle him, and kiss his lips, his eyes, and his cheeks. He was naturally opposed to all demonstration, but this impetuous love moved him, and he often submitted to her petting. He remembered also how sweet it was to caress her. To remember all this, when that sweet child had become what she now was, a creature of whom he could not think without loathing. +He also recalled the time when she was growing into womanhood, and the curious feeling of fear and anger that he experienced when he became aware that men regarded her as a woman. He thought of his jealous love when she came coquettishly to him dressed for a ball, and knowing that she was pretty. He dreaded the passionate glances which fell upon her, that she not only did not understand but rejoiced in. “Yes,” thought he, “that superstition of woman’s purity! Quite the contrary, they do not know shame–they lack this sense.” He remembered how, quite inexplicably to him, she had refused two very good suitors. She had become more and more fascinated by her own success in the round of gaieties she lived in. + +But this success could not last long. A year passed, then two, then three. She was a familiar figure, beautiful–but her first youth had passed, and she had become somehow part of the ball-room furniture. Michael Ivanovich remembered how he had realised that she was on the road to spinsterhood, and desired but one thing for her. He must get her married off as quickly as possible, perhaps not quite so well as might have been arranged earlier, but still a respectable match. + +But it seemed to him she had behaved with a pride that bordered on insolence. Remembering this, his anger rose more and more fiercely against her. To think of her refusing so many decent men, only to end in this disgrace. “Oh, oh!” he groaned again. + +Then stopping, he lit a cigarette, and tried to think of other things. He would send her money, without ever letting her see him. But memories came again. He remembered–it was not so very long ago, for she was more than twenty then–her beginning a flirtation with a boy of fourteen, a cadet of the Corps of Pages who had been staying with them in the country. She had driven the boy half crazy; he had wept in his distraction. Then how she had rebuked her father severely, coldly, and even rudely, when, to put an end to this stupid affair, he had sent the boy away. She seemed somehow to consider herself insulted. Since then father and daughter had drifted into undisguised hostility. + +“I was right,” he said to himself. “She is a wicked and shameless woman.” + +And then, as a last ghastly memory, there was the letter from Moscow, in which she wrote that she could not return home; that she was a miserable, abandoned woman, asking only to be forgiven and forgotten. Then the horrid recollection of the scene with his wife came to him; their surmises and their suspicions, which became a certainty. The calamity had happened in Finland, where they had let her visit her aunt; and the culprit was an insignificant Swede, a student, an empty-headed, worthless creature–and married. + +All this came back to him now as he paced backwards and forwards on the bedroom carpet, recollecting his former love for her, his pride in her. He recoiled with terror before the incomprehensible fact of her downfall, and he hated her for the agony she was causing him. He remembered the conversation with his sister-in-law, and tried to imagine how he might forgive her. But as soon as the thought of “him” arose, there surged up in his heart horror, disgust, and wounded pride. He groaned aloud, and tried to think of something else. + +“No, it is impossible; I will hand over the money to Peter to give her monthly. And as for me, I have no longer a daughter.” + +And again a curious feeling overpowered him: a mixture of self-pity at the recollection of his love for her, and of fury against her for causing him this anguish. + +II + +DURING the last year Lisa had without doubt lived through more than in all the preceding twenty-five. Suddenly she had realised the emptiness of her whole life. It rose before her, base and sordid– this life at home and among the rich set in St. Petersburg– this animal existence that never sounded the depths, but only touched the shallows of life. +It was well enough for a year or two, or perhaps even three. But when it went on for seven or eight years, with its parties, balls, concerts, and suppers; with its costumes and coiffures to display the charms of the body; with its adorers old and young, all alike seemingly possessed of some unaccountable right to have everything, to laugh at everything; and with its summer months spent in the same way, everything yielding but a superficial pleasure, even music and reading merely touching upon life’s problems, but never solving them–all this holding out no promise of change, and losing its charm more and more–she began to despair. She had desperate moods when she longed to die. + +Her friends directed her thoughts to charity. On the one hand, she saw poverty which was real and repulsive, and a sham poverty even more repulsive and pitiable; on the other, she saw the terrible indifference of the lady patronesses who came in carriages and gowns worth thousands. Life became to her more and more unbearable. She yearned for something real, for life itself–not this playing at living, not this skimming life of its cream. Of real life there was none. The best of her memories was her love for the little cadet Koko. That had been a good, honest, straight-forward impulse, and now there was nothing like it. There could not be. She grew more and more depressed, and in this gloomy mood she went to visit an aunt in Finland. The fresh scenery and surroundings, the people strangely different to her own, appealed to her at any rate as a new experience. + +How and when it all began she could not clearly remember. Her aunt had another guest, a Swede. He talked of his work, his people, the latest Swedish novel. Somehow, she herself did not know how that terrible fascination of glances and smiles began, the meaning of which cannot be put into words. + +These smiles and glances seemed to reveal to each, not only the soul of the other, but some vital and universal mystery. Every word they spoke was invested by these smiles with a profound and wonderful significance. Music, too, when they were listening together, or when they sang duets, became full of the same deep meaning. So, also, the words in the books they read aloud. Sometimes they would argue, but the moment their eyes met, or a smile flashed between them, the discussion remained far behind. They soared beyond it to some higher plane consecrated to themselves. + +How it had come about, how and when the devil, who had seized hold of them both, first appeared behind these smiles and glances, she could not say. But, when terror first seized her, the invisible threads that bound them were already so interwoven that she had no power to tear herself free. She could only count on him and on his honour. She hoped that he would not make use of his power; yet all the while she vaguely desired it. + +Her weakness was the greater, because she had nothing to support her in the struggle. She was weary of society life and she had no affection for her mother. Her father, so she thought, had cast her away from him, and she longed passionately to live and to have done with play. Love, the perfect love of a woman for a man, held the promise of life for her. Her strong, passionate nature, too, was dragging her thither. In the tall, strong figure of this man, with his fair hair and light upturned moustache, under which shone a smile attractive and compelling, she saw the promise of that life for which she longed. And then the smiles and glances, the hope of something so incredibly beautiful, led, as they were bound to lead, to that which she feared but unconsciously awaited. +Suddenly all that was beautiful, joyous, spiritual, and full of promise for the future, became animal and sordid, sad and despairing. + +She looked into his eyes and tried to smile, pretending that she feared nothing, that everything was as it should be; but deep down in her soul she knew it was all over. She understood that she had not found in him what she had sought; that which she had once known in herself and in Koko. She told him that he must write to her father asking her hand in marriage. This he promised to do; but when she met him next he said it was impossible for him to write just then. She saw something vague and furtive in his eyes, and her distrust of him grew. The following day he wrote to her, telling her that he was already married, though his wife had left him long since; that he knew she would despise him for the wrong he had done her, and implored her forgiveness. She made him come to see her. She said she loved him; that she felt herself bound to him for ever whether he was married or not, and would never leave him. The next time they met he told her that he and his parents were so poor that he could only offer her the meanest existence. She answered that she needed nothing, and was ready to go with him at once wherever he wished. He endeavoured to dissuade her, advising her to wait; and so she waited. But to live on with this secret, with occasional meetings, and merely corresponding with him, all hidden from her family, was agonising, and she insisted again that he must take her away. At first, when she returned to St. Petersburg, be wrote promising to come, and then letters ceased and she knew no more of him. + +She tried to lead her old life, but it was impossible. She fell ill, and the efforts of the doctors were unavailing; in her hopelessness she resolved to kill herself. But how was she to do this, so that her death might seem natural? She really desired to take her life, and imagined that she had irrevocably decided on the step. So, obtaining some poison, she poured it into a glass, and in another instant would have drunk it, had not her sister’s little son of five at that very moment run in to show her a toy his grandmother had given him. She caressed the child, and, suddenly stopping short, burst into tears. + +The thought overpowered her that she, too, might have been a mother had he not been married, and this vision of motherhood made her look into her own soul for the first time. She began to think not of what others would say of her, but of her own life. To kill oneself because of what the world might say was easy; but the moment she saw her own life dissociated from the world, to take that life was out of the question. She threw away the poison, and ceased to think of suicide. + +Then her life within began. It was real life, and despite the torture of it, had the possibility been given her, she would not have turned back from it. She began to pray, but there was no comfort in prayer; and her suffering was less for herself than for her father, whose grief she foresaw and understood. + +Thus months dragged along, and then something happened which entirely transformed her life. One day, when she was at work upon a quilt, she suddenly experienced a strange sensation. No–it seemed impossible. Motionless she sat with her work in hand. Was it possible that this was IT. Forgetting everything, his baseness and deceit, her mother’s querulousness, and her father’s sorrow, she smiled. She shuddered at the recollection that she was on the point of killing it, together with herself. +She now directed all her thoughts to getting away–somewhere where she could bear her child–and become a miserable, pitiful mother, but a mother withal. Somehow she planned and arranged it all, leaving her home and settling in a distant provincial town, where no one could find her, and where she thought she would be far from her people. But, unfortunately, her father’s brother received an appointment there, a thing she could not possibly foresee. For four months she had been living in the house of a midwife– one Maria Ivanovna; and, on learning that her uncle had come to the town, she was preparing to fly to a still remoter hiding-place. + +III + +MICHAEL IVANOVICH awoke early next morning. He entered his brother’s study, and handed him the cheque, filled in for a sum which he asked him to pay in monthly instalments to his daughter. He inquired when the express left for St. Petersburg. The train left at seven in the evening, giving him time for an early dinner before leaving. He breakfasted with his sister-in-law, who refrained from mentioning the subject which was so painful to him, but only looked at him timidly; and after breakfast he went out for his regular morning walk. + +Alexandra Dmitrievna followed him into the hall. + +“Go into the public gardens, Michael–it is very charming there, and quite near to Everything,” said she, meeting his sombre looks with a pathetic glance. + +Michael Ivanovich followed her advice and went to the public gardens, which were so near to Everything, and meditated with annoyance on the stupidity, the obstinacy, and heartlessness of women. + +“She is not in the very least sorry for me,” he thought of his sister-in-law. “She cannot even understand my sorrow. And what of her?” He was thinking of his daughter. “She knows what all this means to me–the torture. What a blow in one’s old age! My days will be shortened by it! But I’d rather have it over than endure this agony. And all that ‘pour les beaux yeux d’un chenapan’–oh!” he moaned; and a wave of hatred and fury arose in him as he thought of what would be said in the town when every one knew. (And no doubt every one knew already.) Such a feeling of rage possessed him that he would have liked to beat it into her head, and make her understand what she had done. These women never understand. “It is quite near Everything,” suddenly came to his mind, and getting out his notebook, he found her address. Vera Ivanovna Silvestrova, Kukonskaya Street, Abromov’s house. She was living under this name. He left the gardens and called a cab. + +“Whom do you wish to see, sir?” asked the midwife, Maria Ivanovna, when he stepped on the narrow landing +of the steep, stuffy staircase. + +“Does Madame Silvestrova live here?” + +“Vera Ivanovna? Yes; please come in. She has gone out; she’s gone to the shop round the corner. + But she’ll be back in a minute.” + +Michael Ivanovich followed the stout figure of Maria Ivanovna into a tiny parlour, and from the next room came the screams of a baby, sounding cross and peevish, which filled him with disgust. They cut him like a knife. + +Maria Ivanovna apologised, and went into the room, and he could hear her soothing the child. The child became quiet, and she returned. + +“That is her baby; she’ll be back in a minute. You are a friend of hers, I suppose?” + +“Yes–a friend–but I think I had better come back later on,” said Michael Ivanovich, preparing to go. It was too unbearable, this preparation to meet her, and any explanation seemed impossible. + +He had just turned to leave, when he heard quick, light steps on the stairs, and he recognised Lisa’s voice. + +“Maria Ivanovna–has he been crying while I’ve been gone–I was–“ + +Then she saw her father. The parcel she was carrying fell from her hands. +“Father!” she cried, and stopped in the doorway, white and trembling. + +He remained motionless, staring at her. She had grown so thin. Her eyes were larger, her nose sharper, her hands worn and bony. He neither knew what to do, nor what to say. He forgot all his grief about his dishonour. He only felt sorrow, infinite sorrow for her; sorrow for her thinness, and for her miserable rough clothing; and most of all, for her pitiful face and imploring eyes. + +“Father–forgive,” she said, moving towards him. + +“Forgive–forgive me,” he murmured; and he began to sob like a child, kissing her face and hands, and wetting them with his tears. + +In his pity for her he understood himself. And when he saw himself as he was, + + he realised how he had wronged her, how guilty he had been in his pride, in his coldness, even in his anger towards her. He was glad that it was he who was guilty, and that he had nothing to forgive, but that he himself needed forgiveness. She took him to her tiny room, and told him how she lived; but she did not show him the child, nor did she mention the past, knowing how painful it would be to him. + +He told her that she must live differently. + +“Yes; if I could only live in the country,” said she. + +“We will talk it over,” he said. Suddenly the child began to wail and to scream. She opened her eyes very wide; and, not taking them from her father’s face, remained hesitating and motionless. + + +“Well–I suppose you must feed him,” said Michael Ivanovich, and frowned with the obvious effort. + +She got up, and suddenly the wild idea seized her to show him whom she loved so deeply the thing she now loved best of all in the world. But first she looked at her father’s face. Would he be angry or not? His face revealed no anger, only suffering. + +“Yes, go, go,” said he; “God bless you. Yes. I’ll come again to-morrow, and we will decide. Good-bye, my darling– good-bye.” Again he found it hard to swallow the lump in his throat. + +When Michael Ivanovich returned to his brother’s house, Alexandra Dmitrievna immediately rushed to him. + +“Well?” + +“Well? Nothing.” + +“Have you seen?” she asked, guessing from his expression that something had happened. + +“Yes,” he answered shortly, and began to cry. “I’m getting old and stupid,” said he, mastering his emotion. + +“No; you are growing wise–very wise.” \ No newline at end of file diff --git a/src/UnigramWordPredictorTest.java b/src/UnigramWordPredictorTest.java index ca6a6f9..bcffc42 100644 --- a/src/UnigramWordPredictorTest.java +++ b/src/UnigramWordPredictorTest.java @@ -5,8 +5,24 @@ import static org.junit.jupiter.api.Assertions.*; class UnigramWordPredictorTest { - - // Wave 4 - Testing the train method +// Wave 4 + /** + * Tests the train method by checking that the generated neighbor map matches the expected map. + * + * The training data simulates the tokens: + * "the cat sat. the cat slept. the dog barked." + * + * This results in the following sequences: + * - "the" is followed by "cat", then "cat", and finally "dog". + * - "cat" is followed by "sat" and then "slept". + * - "barked", "sat", and "slept" are both followed by a period ("."). + * - "dog" is followed by "barked". + * - is followed by a period ("."). + * - "." is followed by the word "the" twice. + * + * The expected neighbor map is checked to see if it matches this pattern. + * The test does not care about the order of the map or the lists. + */ @Test void testTrainAndGetNeighborMap() { // Simulated training text with tokenized words @@ -14,19 +30,16 @@ void testTrainAndGetNeighborMap() { List.of("the", "cat", "sat", ".", "the", "cat", "slept", ".", "the", "dog", "barked", ".") ); - // Create predictor and train it UnigramWordPredictor predictor = new UnigramWordPredictor(fakeTokenizer); predictor.train(null); // Scanner input is ignored by FakeTokenizer - // Get the generated neighbor map Map> neighborMap = predictor.getNeighborMap(); - // Sort lists inside the map for easy comparison for (List values : neighborMap.values()) { values.sort(null); } + // Pre-sorted expected map - // Expected word mappings based on training text Map> expectedMap = Map.of( "the", List.of("cat", "cat", "dog"), "cat", List.of("sat", "slept"), @@ -37,23 +50,41 @@ void testTrainAndGetNeighborMap() { "barked", List.of(".") ); - // Check if our model created the correct word map assertEquals(expectedMap, neighborMap); } - // Wave 5 - Testing predictNextWord() + // Wave 5 + /** + * Tests the predictNextWord method using a different example to verify that the correct word + * is predicted based on the training data. + * + * The training data simulates the tokens: + * "the quick brown fox. a quick red fox. the slow green turtle." + * + * This results in the following patterns: + * - "the" is followed by "quick" and "slow". + * - "a" is followed by "quick". + * - "quick" is followed by "brown" and "red". + * - "fox" is followed by a period "." twice. + * - "slow" is followed by "green". + * - "green" is followed by "turtle". + * - "turtle" is followed by a period ".". + * - A period "." is followed by "the" twice and "a" once. + * + * The test verifies that the predictions for various words are consistent with these patterns. + */ + @Test void testPredictNextWord() { - // Simulated tokenized words for testing predictions + // Use a fake tokenizer with a new set of predefined tokens + FakeTokenizer fakeTokenizer = new FakeTokenizer( List.of("the", "quick", "brown", "fox", ".", "a", "quick", "red", "fox", ".", "the", "slow", "green", "turtle", ".") ); - // Create and train predictor UnigramWordPredictor predictor = new UnigramWordPredictor(fakeTokenizer); predictor.train(null); - // Check word predictions based on training assertTrue(List.of("quick", "slow").contains(predictor.predictNextWord(List.of("the")))); assertEquals("quick", predictor.predictNextWord(List.of("a"))); assertTrue(List.of("brown", "red").contains(predictor.predictNextWord(List.of("quick")))); @@ -63,10 +94,27 @@ void testPredictNextWord() { assertTrue(List.of("the", "a").contains(predictor.predictNextWord(List.of(".")))); } - // Wave 5 - Probabilistic test for predictNextWord() + // Wave 5 + /** + * Tests the predictNextWord method probabilistically by performing multiple trials to check if + * the predicted words appear with the expected frequencies. + * + * The training data simulates the tokens: + * "the cat sat. the cat slept. the dog barked." + * + * Expected probabilities based on the training data: + * - "the" is followed by "cat" twice and "dog" once, so "cat" should appear 2/3 of the time, + * and "dog" should appear 1/3 of the time. + * - "cat" is followed by "sat" and "slept", so each should appear 50% of the time. + * - "dog" is always followed by "barked". + * - Each period is always followed by "the". + * + * The test runs multiple trials to estimate these probabilities and compares them to the + * expected values with some tolerance for variation. + */ + @Test void testPredictNextWordProbabilistically() { - // Training data FakeTokenizer fakeTokenizer = new FakeTokenizer( List.of("the", "cat", "sat", ".", "the", "cat", "slept", ".", "the", "dog", "barked", ".") ); @@ -76,9 +124,8 @@ void testPredictNextWordProbabilistically() { // Number of trials for probability check int trials = 10000; - double tolerance = 0.05; // Allow 5% deviation + double tolerance = 0.05; - // Expected probabilities based on word frequency Map> expectedProbabilities = Map.of( "the", Map.of("cat", 2.0 / 3.0, "dog", 1.0 / 3.0), "cat", Map.of("sat", 0.5, "slept", 0.5), @@ -86,21 +133,17 @@ void testPredictNextWordProbabilistically() { ".", Map.of("the", 1.0) ); - // Check predictions for each word for (String word : expectedProbabilities.keySet()) { Map counts = new HashMap<>(); Map expected = expectedProbabilities.get(word); - // Initialize word count expected.keySet().forEach(nextWord -> counts.put(nextWord, 0)); - // Run trials to collect frequency data for (int i = 0; i < trials; i++) { String predictedWord = predictor.predictNextWord(List.of(word)); counts.put(predictedWord, counts.getOrDefault(predictedWord, 0) + 1); } - // Compare observed vs expected probability for (String nextWord : expected.keySet()) { double observedFrequency = counts.get(nextWord) / (double) trials; double expectedFrequency = expected.get(nextWord);