Python:为什么我在函数中得到“zero division error:division by zero”?

2024-10-02 20:43:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是统计一个文件中属于特定时区的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和其他使用abc和{}进行除法的总值。在

如果我打印abc、或{}的值,则显示0。我的问题是为什么它们的值是0?abc、和{}的值在if语句中没有变化吗?在


Tags: inforifvaluelongcentralwordsprint
3条回答

eastern除以0。你可以通过做

easternTotal = eastern/a if a > 0 else eastern

因此,唯一可能发生的方法是,无法到达递增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()先获取数据。

相关问题 更多 >