Python:提取特定列数据并将其存储到变量中

2024-04-26 03:46:27 发布

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

我有一个csv文件,我想从中提取ratings和comments字段,并将其存储在两个变量中-rating和comment。这个过程完成后,我需要查看提取的数据。CSV文件中存储的数据如下:

enter image description here

在我的dataclean python文件中,目前编写的代码是:

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

我得到了以下错误:

^{pr2}$

也可以有人建议如何从这个文件在另一个文件访问评级变量主.py计算平均收视率?在


Tags: 文件csvthe数据textinselffor
1条回答
网友
1楼 · 发布于 2024-04-26 03:46:27

csv.DictReader返回一个迭代器,该迭代器将行生成为dict,因此您应该使用它们的键访问每行的列:

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

您还应该删除跳过标题的行,因为csv.DictReader已经将第一行作为标题读取。在

相关问题 更多 >