【发布时间】:2017-11-15 16:39:49
【问题描述】:
我的目标是计算文件中属于特定时区的推文总数。 我有以下函数(我已经用 cmets 注意到函数末尾附近的问题区域):
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("[],!?#./-=+_@")
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 和使用 a、b、c 和 d 进行除法的其他总值出现 ZeroDivisionError: division by zero 错误。
如果我打印a、b、c 或d 的值,则会显示0。我的问题是为什么它们的值是 0? a、b、c 和 d 的值在 if 语句中没有变化吗?
【问题讨论】:
-
如果
inFile为空,或者一行不包含lat和long,当传递给getTimeZone时返回'eastern',那么a将是0.阅读如何创建minimal reproducible example。 -
请修正你的缩进并显示你是如何调用函数的。
标签: python python-3.x pycharm