この記事では主に Python で単語数をカウントする詳細なアイデアを紹介します。また、興味のある方は一緒に見てください
問題の説明:
Python を使用する関数 count_words() を実装します。この関数は文字列 s と数値 n を受け取り、s 内で最も頻繁に出現する n 個の単語を返します。戻り値は、最も出現頻度の高い n 個の単語とその回数を含むタプルのリストです。つまり、[(
すべての入力は小文字であり、句読点やその他の文字は含まれていない (文字と 1 つのスペースのみ) と想定できます。同じ数の出現がある場合は、アルファベット順に並べられます。
例:
print count_words("betty bought a bit of butter but the butter was bitter",3)
出力:
[('butter', 2), ('a', 1), ('betty', 1)]
解決するアイデア問題:
1. 文字列 s を空白で分割して、すべての単語リストを取得します。例: ['betty'、'bought'、'a'、'bit'、'of'、'butter'、 ' but', 'the', 'butter', 'was', 'bitter']
2. マップリストを作成し、split_s を次のようなタプルのリストに変換します: [('betty', 1), ( '買った', 1), ('a', 1), ('bit', 1), ('of', 1), ('butter', 1), ('but', 1), ('the ' , 1), ('butter', 1), ('was', 1), ('bitter', 1)]
3. タプルの最初のインデックス値が同じ場合、マップリスト内の要素をマージします。 、その後、その 2 番目のインデックス値が追加されます。
// 注:defaultdict を使用する準備をします。取得したデータは次のとおりです: {'betty': 1, 'bought': 1, 'a': 1, 'bit': 1, 'of': 1, 'butter': 2, 'but': 1, 'the ': 1, 'was': 1, 'bitter': 1}
4. キーでアルファベット順に並べ替えると、次のようになります: [('a', 1), ('betty', 1), ( 'ビット', 1), ('苦い', 1), ('買った', 1), ('しかし', 1), ('バター', 2), ('の', 1), ('ザ ' , 1), ('was', 1)]
5. 二次ソートを実行し、値でソートし、次を取得します: [('butter', 2), ('a', 1), ('betty ' 、1)、('ビット'、1)、('苦い'、1)、('買った'、1)、('しかし'、1)、('の'、1)、('その'、1 ), ('was', 1)]
6. スライスを使用して * より高い頻度でデータのグループを抽出します
概要:defaultdict を使用しない並べ替え結果も python3 では正しいですが、python2 では正しくありません。 defaultdict 自体には順序がありません。リストを区別するには、ソートする必要があります。
サードパーティのモジュールを使用せずに自分で作成してみることもできます
解決策 1 (defaultdict を使用):
from collections import defaultdict """Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" split_s = s.split() map_list = [(k,1) for k in split_s] output = defaultdict(int) for d in map_list: output[d[0]] += d[1] output1 = dict(output) top_n = sorted(output1.items(), key=lambda pair:pair[0], reverse=False) top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True) return top_n[:n] def test_run(): """Test count_words() with some inputs.""" print(count_words("cat bat mat cat bat cat", 3)) print(count_words("betty bought a bit of butter but the butter was bitter", 4)) if __name__ == '__main__': test_run()
解決策 2 (Counter を使用)
from collections import Counter """Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" split_s = s.split() split_s = Counter(name for name in split_s) print(split_s) top_n = sorted(split_s.items(), key=lambda pair:pair[0], reverse=False) print(top_n) top_n = sorted(top_n, key=lambda pair:pair[1], reverse=True) print(top_n) return top_n[:n] def test_run(): """Test count_words() with some inputs.""" print(count_words("cat bat mat cat bat cat", 3)) print(count_words("betty bought a bit of butter but the butter was bitter", 4)) if __name__ == '__main__': test_run()
関連する推奨事項:
以上がPythonで単語数をカウントする考え方を詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト

toaccesselementsinapythonlist、useindexing、negativeindexing、slicing、oriteration.1)indexingstartsat0.2)negativeindexingAcsesess.3)slicingextractStions.4)reterationSuseSuseSuseSuseSeSeS forLoopseCheckLentlentlentlentlentlentlenttodExeror。

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

ホットトピック









