Pythonの演習を行っています。
全く分からず、丸投げになってしまうことをお許しください。
回答よろしくお願いいたします。
以下が問題です。
「ファイルalice-wonderland.txtに書かれたテキストを読み、各単語の出現回数を計測し、出現回数が2以上の単語を降順にソートして出力するプログラムを書きなさい。正規表現を扱るreモジュールを使用します。」
以下が出力結果です。
単語の個数 26
単語の降順リスト
[('the', 12), ('in', 8), ('a', 7), ('and', 7), ('to', 6), ('of', 5),
('it', 5), ('tale', 4), ('one', 4), ('with', 3), ('little', 3), ('by', 3), ('we', 2),
('our', 2), ('are', 2), ('while', 2), ('three', 2), ('such', 2), ('beneath', 2),
('fancy', 2), ('land', 2), ('story', 2), ('next', 2), ('time', 2), ('is', 2),
('thus', 2)]
私の作成途中のプログラム(編集しました)です。
Python
1import re 2 3with open('alice-wonderland.txt', 'r', encoding='utf-8') as f: 4 data = f.read() 5 data=data.lower() 6 data=re.sub(r'[^a-z]', ' ', data) 7words={} 8for word in data.split(): 9 words[word]=words.get(word,0)+1 10 11d=[(v,k) for k,v in words.items() if v>=2] 12d.sort() 13d.reverse() 14 15l=0 16for word,count in d: 17 l+=1 18print('単語の個数',l) 19print('単語の降順リスト') 20print(d)
上記のプログラムの出力結果です。
Python
1単語の個数 28 2単語の降順リスト 3[(12, 'the'), (8, 'in'), (7, 'and'), (7, 'a'), (6, 'to'), (5, 'of'), (5, 'it'), (4, 'tale'), (4, 'one'), (3, 'with'), (3, 's'), (3, 'little'), (3, 'by'), (2, 'while'), (2, 'we'), (2, 'time'), (2, 'thus'), (2, 'three'), (2, 'such'), (2, 'story'), (2, 'our'), (2, 'next'), (2, 'land'), (2, 'is'), (2, 'fancy'), (2, 'd'), (2, 'beneath'), (2, 'are')]
ファイルalice-wonderland.txtの内容を以下に記載します。
Python
1All in the golden afternoon 2 Full leisurely we glide; 3 For both our oars, with little skill, 4 By little arms are plied, 5 While little hands make vain pretence 6 Our wanderings to guide. 7 8Ah, cruel Three! In such an hour. 9 Beneath such dreamy weather. 10 To beg a tale of breath too weak 11 To stir the tiniest feather! 12 Yet what can one poor voice avail 13 Against three tongues together? 14 15Imperious Prima flashes forth 16 Her edict "to begin it"— 17 In gentler tone Secunda hopes 18 "There will he nonsense in it!"— 19 While Tertia interrupts the tale 20 Not more than once a minute. 21 22Anon, to sudden silence won, 23 In fancy they pursue 24 The dream-child moving through a land 25 Of wonders wild and new, 26 In friendly chat with bird or beast— 27 And half believe it true. 28 29And ever, as the story drained 30 The wells of fancy dry, 31 And faintly strove that weary one 32 To put the subject by, 33 "The rest next time—" "It is next time!" 34 The happy voices cry. 35 36Thus grew the tale of Wonderland: 37 Thus slowly, one by one, 38 Its quaint events were hammered out— 39 And now the tale is done, 40 And home we steer, a merry crew, 41 Beneath the setting' sun. 42 43Alice! a childish story take, 44 And with a gentle hand 45 Lay it where Childhood's dreams are twined 46 In Memory's mystic band, 47 Like pilgrim's wither'd wreath of flowers 48 Pluck'd in a far-off land. 49
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/02/04 04:32
2021/02/04 04:52
2021/02/04 04:56
2021/02/04 05:04
2021/02/04 05:23
2021/02/04 05:25
2021/02/04 05:30
2021/02/04 06:31