私はPythonを学んでいて、テキスト内の文字数を数え、それらの相対頻度を計算するスクリプトを書きたいと思っていました。しかし、最初に、ファイルの長さを知りたいと思いました。私の意図は、スクリプトがすべての文字を数えて行から行へと移動する間、現在の行と合計行数を出力するので、どれだけの時間がかかるかを知ることができるということです。
単純なforループを実行して行数をカウントし、次に別のforループを実行して文字をカウントして辞書に入れました。ただし、最初のforループを使用してスクリプトを実行すると、スクリプトは早期に停止します。私の知る限り、2番目のforループには入りません。このループを削除すると、残りのコードは正常に処理されます。これは何が原因ですか?
コードを失礼します。初歩的ですが、私はそれを誇りに思っています。
私のコード:
import string
fname = input ('Enter a file name: ')
try:
fhand = open(fname)
except:
print ('Cannot open file.')
quit()
#Problematic bit. If this part is present, the script ends abruptly.
#filelength = 0
#for lines in fhand:
# filelength = filelength + 1
counts = dict()
currentline = 1
for line in fhand:
if len(line) == 0: continue
line = line.translate(str.maketrans('','',string.punctuation))
line = line.translate(str.maketrans('','',string.digits))
line = line.translate(str.maketrans('','',string.whitespace))
line = line.translate(str.maketrans('','',""" '"’‘“” """))
line = line.lower()
index = 0
while index < len(line):
if line[index] not in counts:
counts[line[index]] = 1
else:
counts[line[index]] += 1
index += 1
print('Currently at line: ', currentline, 'of', filelength)
currentline += 1
listtosort = list()
totalcount = 0
for (char, number) in list(counts.items()):
listtosort.append((number,char))
totalcount = totalcount + number
listtosort.sort(reverse=True)
for (number, char) in listtosort:
frequency = number/totalcount*100
print ('Character: %s, count: %d, Frequency: %g' % (char, number, frequency))
あなたのやり方は問題ないように見えますが、問題をシミュレートするために、Guttenbergの教科書をダウンロードして保存しました。これはUnicodeの問題です。それを解決する2つの方法。バイナリファイルとして開くか、エンコーディングを追加します。テキストなので、utf-8オプションを使用します。
また、別の方法でコーディングすることをお勧めします。以下は、ファイルを開いた後にファイルを閉じる基本構造です。
filename = "GutenbergBook.txt"
try:
#fhand = open(filename, 'rb')
#open read only and utf-8 encoding
fhand = open(filename, 'r', encoding = 'utf-8')
except IOError:
print("couldn't find the file")
else:
try:
for line in fhand:
#put your code here
print(line)
except:
print("Error reading the file")
finally:
fhand.close()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加