この記事では、Pythonプログラミングを使用してファイルの行数と単語数を数える方法について説明する予定です。
こちらもお読みください。
How to Count Words and Lines – Python Wordcounter
大きなファイルを持っていて、そのファイル内の単語数を把握する必要があるとします。
また、その中に何行のテキストが存在するかも調べたいでしょう。
Pythonを使って、単語と行をカウントするワードカウンタープログラムを作成することができます。
1. サンプルテキストファイルの作成
今回のテキストファイルの作成では、まず変数を作成し、そこに文字列を代入します。
次に、open()関数で書き込み専用モード(‘w’)のファイルを作成し、新しく作成したテキストファイルに文字列変数の内容を書き込んでいきます。
最後に、テキストファイルを閉じます。
それでは、テキストファイルを作成するPythonプログラムを書いてみましょう。
# Create a Python stringstring = """Welcome to Python!
Python is a part of JournalDev IT Services Private Limited."""# Create a sample text file using open() functionfile = open("sample_file.txt", "w", encoding='utf-8')
# Write the above string to the newly created text file# If it is created successfullyif file != None:
file.write(string)
print("Sample text file created and written successfully!!")
else:
print("OSError: File cannot be created!!")
# Close the above text file using close()file.close()
|
結果は以下の通りです。
Sample text file created and written successfully!! |
この記事もチェック:Pythonでcopy関数やpopen関数等を使ってファイルをコピーする方法
2. サンプルテキストファイルの内容を表示する
テキストファイルの作成に成功したので、次に read() 関数を用いてサンプルテキストファイルの内容を読み込み専用モード (‘r’) で変数に読み込んでみます。
そして、Python変数の内容を表示して、ファイルからのテキストを表示します。
最後に、良い習慣として、開いたテキストを閉じて、コードのメモリリークを回避します。
それでは、与えられたテキストファイルを読み込むためのPythonコードを見てみましょう。
# Open the given sample text file using open() function# In read only modefile = open("C:path//sample_file.txt", "r", encoding='utf-8')
# Read the sample text file using the read() function# If it is opened successfullyif file != None:
file_data = file.read()
# Print the content of the sample text file
print("This is the content of the sample text file:)
print(file_data)
else:
print("OSError: File cannot be opend!!")
# Close the above opened text file using close() functionfile.close()
|
結果は以下の通りです。
This is the content of the sample text file:Welcome to Python!Python is a part of JournalDev IT Services Private Limited. |
3. ファイル内の行数と単語数をカウントするアルゴリズム
ファイルの行数と単語数を数えるには、次のような手順で行います。
-
-
line_count&word_countという二つの変数を作成し、ゼロで初期化します。
-
-
-
file_pathという変数を作成し、与えられたテキストファイルのフルパスで初期化します。
-
-
-
open()関数を使用して、与えられたテキストファイルを読み取り専用モード (‘r’) で開きます。
-
-
- 開いたテキストファイルを一行ずつ読み、繰り返し行うたびに
line_countを 1 つずつ増やしていく。
- 開いたテキストファイルを一行ずつ読み、繰り返し行うたびに
-
-
len()関数とsplit()関数を用いて、読み込んだ各行の単語数を数える。
-
-
- 各行の単語数を
word_countに追加します。
- 各行の単語数を
-
-
close()関数を用いて、開いているテキストファイルを閉じる。
-
-
-
line_countとword_count変数の最終的な値を表示します。
-
4. ファイルの行数と単語数をカウントするPythonコード
上記の行数と単語数をカウントするアルゴリズムをPythonコードで実装してみましょう。
# Create two counter variables# And initialize them with zeroline_count = 0
word_count = 0
# Open the given sample text file using open() functionfile = open("C:path//sample_file.txt", "r", encoding='utf-8')
# Perform all the operations using the sample text file# If it is opened successfullyif file != None:
# Iterate over the opened file
# To the number of lines and words in it
for line in file:
# Increment the line counter variable
line_count = line_count + 1
# Find the number of words in each line
words = len(line.split())
# Add the number of words in each line
# To the word counter variable
word_count = word_count + words
else:
print("OSError: File cannot be opend!!")
# Close the above opened text file using close() functionfile.close()
# Print the final results using the final values # Of the line_count and word_count variablesprint(f")
print(f")
|
結果は以下の通りです。
Total number of lines in the given file: 2Total number of words in the given file: 13 |
まとめ
この記事では、以下のことを学びました。
- Pythonでテキストファイルを作成するには?
- Pythonでテキストファイルの内容を読み取るには?
- 与えられたテキストファイルの行数と単語数をカウントするアルゴリズム。
- Pythonを使ってテキストファイルの行数と単語数を数えるには?
あなたが明確であり、あなた自身でこれらのタスクを実行する準備ができていることを願っています。
ありがとうございました!このようなPythonのチュートリアルをもっと見るために私たちにご期待ください。