ホームページ  >  記事  >  バックエンド開発  >  Pythonでtxtファイル内の単語数を数える方法

Pythonでtxtファイル内の単語数を数える方法

尚
オリジナル
2019-07-06 10:28:567812ブラウズ

Pythonでtxtファイル内の単語数を数える方法

Python で txt ファイル内の単語数をカウントするには、rstrip 関数と len 関数を使用できます。

以下は、White Night Walk.txt 内の単語数を数えます:

file_name = '白夜行.txt'
try:
    with open(file_name, encoding='utf8') as file_obj:
    #由于书名不是英文,要加上 encoding='utf8'
        contents = file_obj.read()
except FileNotFoundError:
    msg = 'Sorry, the file' + file_name + ' does not exist.'
    print(msg)
else:
    words = contents.rstrip()
    num_words = len(words)
    print('The file ' + file_name + ' has about ' + str(num_words) + ' words.')

結果:

The file 白夜行.txt has about 487761 words.

Python 関連の技術記事の詳細については、# を参照してください。 ##Pythonチュートリアル学習用コラム!

以上がPythonでtxtファイル内の単語数を数える方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。