-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentimental.py
More file actions
80 lines (63 loc) · 2.32 KB
/
Sentimental.py
File metadata and controls
80 lines (63 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# filepath: /amazon-sentiments/amazon-sentiments/Sentimental.py
# -------------------------------
# Amazon Review Sentiment Analysis
# -------------------------------
# ✅ Import Libraries
import pandas as pd
import numpy as np
from faker import Faker
import random
from textblob import TextBlob
# -------------------------------
# STEP 1: Generate Synthetic Amazon Review Dataset
# -------------------------------
fake = Faker()
Faker.seed(42)
random.seed(42)
# Define product categories for realism
categories = ['Electronics', 'Books', 'Clothing', 'Sports', 'Home']
# Number of reviews
num_reviews = 500
data = []
for i in range(1, num_reviews + 1):
review_id = i
customer_id = fake.uuid4()
product_id = random.randint(1000, 9999)
category = random.choice(categories)
# Generate random review text (short sentences)
review_text = fake.sentence(nb_words=random.randint(8, 20))
# Simulate a rating (1-5 stars)
rating = random.randint(1, 5)
data.append([review_id, customer_id, product_id, category, review_text, rating])
# Create DataFrame
df = pd.DataFrame(data, columns=['review_id', 'customer_id', 'product_id', 'category', 'review_text', 'rating'])
# -------------------------------
# STEP 2: Sentiment Analysis using TextBlob
# -------------------------------
def get_sentiment(text):
analysis = TextBlob(text)
polarity = analysis.sentiment.polarity # range: -1 (negative) to +1 (positive)
if polarity > 0.1:
return 'Positive'
elif polarity < -0.1:
return 'Negative'
else:
return 'Neutral'
def get_polarity(text):
return round(TextBlob(text).sentiment.polarity, 3)
# Apply sentiment analysis
df['sentiment'] = df['review_text'].apply(get_sentiment)
df['polarity'] = df['review_text'].apply(get_polarity)
# -------------------------------
# STEP 3: Save to CSV
# -------------------------------
# Unique Customers
customers_df = df[['customer_id']].drop_duplicates()
customers_df['name'] = [fake.name() for _ in range(len(customers_df))]
customers_df['region'] = [fake.state() for _ in range(len(customers_df))]
customers_df.to_csv('customers.csv', index=False)
# Unique Products
products_df = df[['product_id', 'category']].drop_duplicates()
products_df.to_csv('products.csv', index=False)
# Reviews (already have df)
df.to_csv('reviews.csv', index=False)