私の目標は、特定の時間帯に属するファイルのつぶやきの総数を数えることです。Python:関数で "ZeroDivisionError:division by zero"が表示されるのはなぜですか?
def readTweets(inFile, wordsName):
words = []
lat = 0
long = 0
keyword = keywords(wordsName)
sents = keywordSentiment(wordsName)
value = 0
eastern = 0
central = 0
mountain = 0
pacific = 0
a = 0
b = 0
c = 0
d = 0
easternTweets = 0
centralTweets = 0
mountainTweets = 0
pacificTweets = 0
for line in inFile:
entry = line.split()
for n in range(0, len(entry) - 1):
entry[n] = entry[n].strip("[],!?#./[email protected]")
if n > 4: # n>4 because words begin on 5th index of list
entry[n] = entry[n].lower()
words.append(entry[n])
lat = float(entry[0])
long = float(entry[1])
timezone = getTimeZone(lat, long)
if timezone == "eastern":
easternTweets += 1
if timezone == "central":
centralTweets += 1
if timezone == "mountain":
mountainTweets += 1
if timezone == "pacific":
pacificTweets += 1
for i in range(0, len(words)):
for k in range(0, len(keyword)):
if words[i] == keyword[k]:
value = int(sents[k])
if timezone == "eastern":
eastern += value
a += 1
if timezone == "central":
central += value
b += 1
if timezone == "mountain":
mountain += value
c += 1
if timezone == "pacific":
pacific += value
d += 1
# the values of a,b,c,d are 0
easternTotal = eastern/a # getting error
centralTotal = central/b # for
mountainTotal = mountain/c # these
pacificTotal = pacific/d # values
print("Total tweets per time zone:")
print("Eastern: %d" % easternTweets)
print("Central: %d" % centralTweets)
print("Mountain: %d" % mountainTweets)
print("Pacific: %d" % pacificTweets)
私はeasternTotal
ためZeroDivisionError: division by zero
エラーとa
、b
、c
を使用する他の合計値を取得しています: は、私は、関数以下の(私がコメントを持つ関数の終わり近くにトラブルの領域を指摘している)しています、除算はd
です。
私はa
、b
、c
、またはd
の値を印刷する場合、それは0
を示しています。私の質問はなぜ彼らの値は0ですか? a
,b
,c
およびd
の値は、if
ステートメントで変更されていませんか?
'inFile'が空であるか、' getTimeZone'に渡された 'lat'と' long'が行に含まれていないと 'eastern''を返します。' a'は '0'になります。 [mcve]の作成方法をお読みください。 –
字下げを修正し、どのように関数を呼び出すかを示してください。 – poke