Как я могу прочитать CSV в Python в виде списка без строки (см. Пример ниже)? - PullRequest
0 голосов
/ 12 ноября 2018

CSV в редакторе выглядит:

Review Text;Review Rating
['much', 'write', 'exactly', 'supposed', 'filters', 'pop', 'sounds', 'recordings', 'much', 'crisp', 'one', 'lowest', 'prices', 'pop', 'filters', 'amazon', 'might', 'well', 'buy', 'honestly', 'work', 'despite', 'pricing'];5.0

Читать CSV:

import csv

with open("../Data_filtered/reviews_Musical_Instruments.csv", "r") as csv_file:
    reader = csv.reader(csv_file, delimiter=';', quotechar='|')
    liste = []
    for row in reader:
        liste.extend(row)

Тогда я получаю:

liste = 
['Review Text',
 'Review Rating',
 "['much', 'write', 'exactly', 'supposed', 'filters', 'pop', 'sounds', 'recordings', 'much', 'crisp', 'one', 'lowest', 'prices', 'pop', 'filters', 'amazon', 'might', 'well', 'buy', 'honestly', 'work', 'despite', 'pricing']",
 '5.0']

Но мне нужно (без строки):

liste = 
['Review Text',
 'Review Rating', 'much', 'write', 'exactly', 'supposed', 'filters', 'pop', 'sounds', 'recordings', 'much', 'crisp', 'one', 'lowest', 'prices', 'pop', 'filters', 'amazon', 'might', 'well', 'buy', 'honestly', 'work', 'despite', 'pricing',
 '5.0']

1 Ответ

0 голосов
/ 12 ноября 2018

Вы должны разобрать его, используя ast.literal_eval - хороший выбор:

import csv
import ast

with open("../Data_filtered/reviews_Musical_Instruments.csv", "r") as csv_file:
    reader = csv.reader(csv_file, delimiter=';', quotechar='|')
    liste = []
    for row in reader:
        row[2] = ast.literal_eval(row[2])
        liste.extend(row)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...