2017-12-19 11 views
-1

テキストファイル(file.txt)の内容を読み込んで、1文あたりの平均単語数を計算するPythonコードを書く必要があります。ファイルには1行に1つの文しか含まれていません)。ファイルから単語数を読み込んで平均文を計算する効率的な方法

私はコーディングを行いました。私はそれが他の方法でもっと効率的かどうかを知る必要があります。百万円前もって感謝します。

# This program reads contents of a .txt file and calulate 
# the average number of words per sentence . 

line_count=0 
# open the file.txt for reading 
content_file=open('file.txt','r') 

# calculate the word count of the file 
content=content_file.read() 

words= content.split() 

word_count=len(words) 

# calculate the line count 
for line in open('file.txt'): 

    line_count+=1 

content_file.close() 

# calculate the average words per line 

average_words=word_count/line_count 

# Display the result 

print('The average word count per sentence is', int(average_words)) 

答えて

0

ファイルの内容を一度に1つずつ読み込むので、次のコードは効率的です。

with open(r'C:\Users\lg49242\Desktop\file.txt','r') as content: 
    lineCount = 0 
    Tot_wordCount = 0 
    lines = content.readlines() 
    for line in lines: 
     lineCount = lineCount + 1  
     wordCount = len(line.split()) 
     Tot_wordCount += wordCount 

平均= Tot_wordCount/LINECOUNT

印刷平均

0

ファイルを2回反復する必要はありません:ここ は私のものです。行間を数えて更新するだけです::

0

私の提案は、forループを使用する代わりに、コンテンツを '\ n'で分割して配列の長さを見つけることです。

含量= content_file.read(ファイルのワードカウントを計算

content_file =オープン( 'file.txtを'、 'R')

を読み取るためfile.txtなどを開き)

単語数= LEN(content.split())

LINE_COUNT = LEN(content.split( 'の\ n'))

content_file.close()

が、INT

average_words =単語数/ LINE_COUNT

表示結果

プリント( '文あたりの平均単語数である' 行あたりの平均単語を計算します(average_words))

関連する問題