1

I have a csv file and I want to extract ratings and comments field from it and store it in two variables - rating and comment. After this process is completed I need to view the extracted data. The data stored in the CSV file is as follows:

enter image description here

In my dataclean python file the code written so far is:

class Extractdata:

    def __init__(self, rating, comment):
        self.rating = rating
        self.comment = comment
requirement_list = []
import csv
with open('D://Python//testml//my-tracks-reviews.csv', encoding='utf-8') as fileread:
    filereader = csv.DictReader(fileread, delimiter=';', quotechar='"')
    next(filereader, None)  # Skip the header.
    # Unpack the row directly in the head of the for loop.
    for rating, comment_text in filereader:
        # Get the data in the variable instances.
        rating = int(rating)
        comment = comment_text
        # Now create the requirement instance and append it to the list.
        requirement_list.append(Extractdata(rating, comment))

# View the data

and I am getting the following error:

Traceback (most recent call last):
  File "C:/Users/Sam/PycharmProjects/ReqPrio/preprocess.py", line 12, in <module>
    for rating, comment_text in filereader:
ValueError: not enough values to unpack (expected 2, got 1)

Process finished with exit code 1

Also can anyone suggest how to access the ratings variable from this file in another file say main.py to calculate the average of ratings?

1
  • 1
    This error is telling you that filereader is not a list of tuples (or lists), so that you cannot iterate over two elements at at time. Try for x in filereader: print(x), to see what it looks like. Additionally, you should keep to one question per thread. Commented Nov 5, 2018 at 22:30

1 Answer 1

1

csv.DictReader returns an iterator that generates rows as dicts, so you should access the columns of each row with their keys instead:

for row in filereader:
    rating = int(row['rating'])
    comment = row['comment_text']
    requirement_list.append(Extractdata(rating, comment))

You should also remove the line that skips header because csv.DictReader already reads the first row as header for you.

Sign up to request clarification or add additional context in comments.

2 Comments

r = int(row['rating']) KeyError: 'rating' Process finished with exit code 1
It appears that your CSV file isn't parsed correctly by csv.DictReader. Please make sure that ; is really the delimiter for your CSV file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.