2016-11-16 2 views
0

Я изо всех сил пытаюсь понять это. Мне нужно создать объект панды DataFrame со следующими записями для каждого обзора:Python Чтение конкретных данных из текстового файла

  • ID продукта
  • Количество людей, которые голосовали этот отзыв полезным
  • Общее число людей, которые оценили этот отзыв
  • Рейтинг продукта
  • Текст обзора

Если кто-то может даже просто помочь мне начать работу о том, как печатать все микрофильтр t/productID, что было бы оценено.

Вот пример моего текстового файла: (жаль, что я не знаю, как правильно отформатировать его, когда я вхожу на этом сайте)

product/productId: B001E4KFG0 
review/userId: A3SGXH7AUHU8GW 
review/profileName: delmartian 
review/helpfulness: 1/1 
review/score: 5.0 
review/time: 1303862400 
review/summary: Good Quality Dog Food 
review/text: I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most. 

product/productId: B00813GRG4 
review/userId: A1D87F6ZCVE5NK 
review/profileName: dll pa 
review/helpfulness: 0/0 
review/score: 1.0 
review/time: 1346976000 
review/summary: Not as Advertised 
review/text: Product arrived labeled as Jumbo Salted Peanuts...the peanuts were actually small sized unsalted. Not sure if this was an error or if the vendor intended to represent the product as "Jumbo". 

product/productId: B000LQOCH0 
review/userId: ABXLMWJIXXAIN 
review/profileName: Natalia Corres "Natalia Corres" 
review/helpfulness: 1/1 
review/score: 4.0 
review/time: 1219017600 
review/summary: "Delight" says it all 
review/text: This is a confection that has been around a few centuries. It is a light, pillowy citrus gelatin with nuts - in this case Filberts. And it is cut into tiny squares and then liberally coated with powdered sugar. And it is a tiny mouthful of heaven. Not too chewy, and very flavorful. I highly recommend this yummy treat. If you are familiar with the story of C.S. Lewis' "The Lion, The Witch, and The Wardrobe" - this is the treat that seduces Edmund into selling out his Brother and Sisters to the Witch. 
+0

В каком поле находится '' 'Количество проголосовавших'''' и' '' число людей, которые оценили '' '? – wwii

ответ

1

Если я понял ваш вопрос, я полагаю, вы хотите прочитать из файла со структурой, которую вы написали. Вы можете использовать следующий код, который будет создавать массив с каждым обзором является словарем:

#Opening your file 
your_file = open('file.txt') 

#Reading every line 
reviews = your_file.readlines() 

reviews_array = [] 
dictionary = {} 

#We are going through every line and skip it when we see that it's a blank line 
for review in reviews: 
    this_line = review.split(":") 
    if len(this_line) > 1: 
     #The blank lines are less than 1 in length after the split 
     dictionary[this_line[0]] = this_line[1].strip() 
     #Every first part before ":" is the key of the dictionary, and the second part id the content. 
    else: 
     #If a blank like was found lets save the object in the array and reset it 
     #for the next review 
     reviews_array.append(dictionary) 
     dictionary = {} 

#Append the last object because it goes out the last else 
reviews_array.append(dictionary) 

print(reviews_array) 

Этого код будет печатать что-то вроде этого:

[ 
{'review/text': 'I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most.', 'review/profileName': 'delmartian', 'review/summary': 'Good Quality Dog Food', 'product/productId': 'B001E4KFG0', 'review/score': '5.0', 'review/time': '1303862400', 'review/helpfulness': '1/1', 'review/userId': 'A3SGXH7AUHU8GW'}, 
{'review/text': 'Product arrived labeled as Jumbo Salted Peanuts...the peanuts were actually small sized unsalted. Not sure if this was an error or if the vendor intended to represent the product as "Jumbo".', 'review/profileName': 'dll pa', 'review/summary': 'Not as Advertised', 'product/productId': 'B00813GRG4', 'review/score': '1.0', 'review/time': '1346976000', 'review/helpfulness': '0/0', 'review/userId': 'A1D87F6ZCVE5NK'}, 
{'review/text': 'bla blas', 'review/profileName': 'Natalia Corres "Natalia Corres"', 'review/summary': '"Delight" says it all', 'product/productId': 'B000LQOCH0', 'review/score': '4.0', 'review/time': '1219017600', 'review/helpfulness': '1/1', 'review/userId': 'ABXLMWJIXXAIN'} 
] 

Вы можете получить доступ к каждому объекту, как это:

for r in reviews_array: 
    print(r['review/userId']) 

И тогда вы будете иметь этот результат:

A3SGXH7AUHU8GW 
A1D87F6ZCVE5NK 
ABXLMWJIXXAIN 
+0

'' 'df = pd.DataFrame (review_array)' '' – wwii

0

Вот начало, я не мог расшифровать пару ваших полей/столбцов, поэтому может потребоваться больше логики и текст массажа. Подобно другим ответам: проанализируйте текст в словарный ключ: пары значений - используя регулярное выражение, найдите пары.

import collections, re 

fields = {'productId':'Product ID', 'score':'Rating', 
      'helpfulness':'Number Voting', 'text':'Review'} 

pattern = r'/([^:]*):\s?(.*)' 
kv = re.compile(pattern) 

data = collections.defaultdict(list) 
with open('file.txt') as f: 
    reviews = f.read() 

for match in kv.finditer(reviews): 
    key, value = match.groups() 
    if key in fields: 
     data[fields[key]].append(value) 

df = pd.DataFrame.from_dict(data) 
Смежные вопросы