我的目标是统计一个文件中属于特定时区的tweet总数。 我有以下功能(我注意到功能末尾附近的故障区域并给出了注释):
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)
我得到了一个ZeroDivisionError: division by zero
错误,easternTotal
和其他使用a
、b
、c
和{
如果我打印a
、b
、c
、或{0
。我的问题是为什么它们的值是0?a
、b
、c
、和{if
语句中没有变化吗?在
将
eastern
除以0
。你可以通过做因此,唯一可能发生的方法是,无法到达递增a、b、c和d的代码。
这有几个原因:
inFile
为空,因此整个for循环从未进入其主体len(words)
为0,因此for循环永远不会进入其主体len(keywords)
为0,因此for循环永远不会进入其主体timezone
的值不是您测试的值words
最初是[]
,因此如果向其添加内容的循环从未运行,则其长度可以保持为0。从这里,我们不可能看到其中的哪一个发生了,但是对于你来说,用一些打印的声明或类似的东西应该很容易。
因为你设置了a,b,c,d=0; 当readTweets(inFile,wordsName)没有得到任何数据时,“eastern/a”可能导致“eastern/0”。
因此,请确保readTweets()先获取数据。
相关问题 更多 >
编程相关推荐