Python error ZeroDivisionError float division by zero

+1 vote

Hey! I am trying to create a plagiarism checker logic. I have used this from GitHub: https://github.com/abhilampard/Simple-Plagiarism-Checker

I am ending up with the following error:

ZeroDivisionError: float division by zero

Code:

from flask import Flask, request, render_template
import re
import math

app = Flask("__name__")

q = ""


@app.route("/")
def loadPage():
    return render_template('index.html', query="aws")


@app.route("/", methods=['POST'])
def cosineSimilarity():
    universalSetOfUniqueWords = []
    matchPercentage = 0

    ####################################################################################################

    inputQuery = request.form['query']
    lowercaseQuery = inputQuery.lower()

    queryWordList = re.sub("[^\w]", " ", lowercaseQuery).split()  # Replace punctuation by space and split
    queryWordList = map(str, queryWordList)

    for word in queryWordList:
        if word not in universalSetOfUniqueWords:
            universalSetOfUniqueWords.append(word)

    ####################################################################################################

    fd = open("database1.txt", "r")
    database1 = fd.read().lower()

    databaseWordList = re.sub("[^\w]", " ", database1).split()  # Replace punctuation by space and split
    databaseWordList = map(str, databaseWordList)

    for word in databaseWordList:
        if word not in universalSetOfUniqueWords:
            universalSetOfUniqueWords.append(word)

    ####################################################################################################

    queryTF = []
    databaseTF = []

    for word in universalSetOfUniqueWords:
        queryTfCounter = 0
        databaseTfCounter = 0

        for word2 in queryWordList:
            if word == word2:
                queryTfCounter += 1
        queryTF.append(queryTfCounter)

        for word2 in databaseWordList:
            if word == word2:
                databaseTfCounter += 1
        databaseTF.append(databaseTfCounter)

    dotProduct = 0
    for i in range(len(queryTF)):
        dotProduct += queryTF[i] * databaseTF[i]

    queryVectorMagnitude = 0
    for i in range(len(queryTF)):
        queryVectorMagnitude += queryTF[i] ** 2
    queryVectorMagnitude = math.sqrt(queryVectorMagnitude)

    databaseVectorMagnitude = 0
    for i in range(len(databaseTF)):
        databaseVectorMagnitude += databaseTF[i] ** 2
    databaseVectorMagnitude = math.sqrt(databaseVectorMagnitude)

    matchPercentage = (float)(dotProduct / (queryVectorMagnitude * databaseVectorMagnitude)) * 100

    '''
    print queryWordList
    print
    print databaseWordList
    print queryTF
    print
    print databaseTF
    '''

    output = "Input query text matches %0.02f%% with database." % matchPercentage

    return render_template('index.html', query=inputQuery, output=output)


app.run(debug=True)
Oct 9, 2019 in Python by Hannah
• 18,520 points
23,157 views

2 answers to this question.

0 votes

remove the following statements from code
    queryWordList = map(str, queryWordList)

    databaseWordList = map(str, databaseWordList

its because map can be iterated only once and we are iterating them twice in this code
   for word in queryWordList:  and second time as
   for word2 in queryWordList:
same for databaseWordList

Hope its helps you
 

If you need to learn more about Python, It's recommended to join Python Programming Training Course today.

answered Nov 13, 2019 by Abhishek
• 150 points
0 votes
The error is thrown in this line

matchPercentage = (float)(dotProduct / (queryVectorMagnitude * databaseVectorMagnitude)) * 100

if the len(databaseTF) returns 0, then databaseVectorMagnitude=0

In the above line the denominator becomes zero. A float number cannot be devided by zero. In this case the express is divided by zero, so the ZeroDivisionError: float division by zero error is thrown in the code. make sure the len(databaseTF) is greater than zero.

Otherwise add the zero check like this

if len(databaseTF) !=0 :

matchPercentage = (float)(dotProduct / (queryVectorMagnitude * databaseVectorMagnitude)) * 100
answered May 21, 2020 by Prabhakar

Related Questions In Python

0 votes
1 answer

Python error "ZeroDivisionError: division by zero"

Catch the error and handle it: try: ...READ MORE

answered May 31, 2019 in Python by Rhea
8,717 views
+2 votes
2 answers

Error while printing hello world in python.

You must be trying this command in ...READ MORE

answered Mar 31, 2018 in Python by GandalfDwhite
• 1,320 points
6,402 views
0 votes
1 answer

Number division in python

For Python 3, use the // operator: q = ...READ MORE

answered Apr 18, 2018 in Python by Nietzsche's daemon
• 4,260 points
620 views
+1 vote
7 answers
0 votes
1 answer

How to sort Counter by value using python?

Use the Counter.most_common() method, it'll sort the items for you: >>> ...READ MORE

answered May 23, 2018 in Python by charlie_brown
• 7,720 points
10,647 views
0 votes
2 answers

Indentation Error in Python

Use tabs instead of spaces. This is ...READ MORE

answered Feb 15, 2019 in Python by Shashank
• 1,370 points
881 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,070 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP