FredZhang7 commited on
Commit
499003f
1 Parent(s): 324be8b

add examples of data preprocessing

Browse files
Files changed (3) hide show
  1. enron_spam.py +24 -0
  2. spam_assassin.js +30 -0
  3. spam_assassin.py +35 -0
enron_spam.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+
4
+ df = pd.read_csv('enron_spam_data.csv')
5
+
6
+ data = []
7
+ for index, row in df.iterrows():
8
+ message = row['Message']
9
+ subject = row['Subject']
10
+ if not message or type(message) == float:
11
+ message = subject
12
+ subject = ''
13
+ elif not subject or type(subject) == float:
14
+ subject = message
15
+ message = ''
16
+ spam_ham = row['Spam/Ham']
17
+ is_spam = 1 if spam_ham.lower() == 'spam' else 0
18
+ text = (str(subject) + """
19
+
20
+ """ + str(message)).strip()
21
+ data.append({'text': text, 'is_spam': is_spam})
22
+
23
+ df = pd.DataFrame(data)
24
+ df.to_csv('enron_spam_clean.csv', index=False)
spam_assassin.js ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const fs = require('fs');
2
+ const corpus = require('@stdlib/datasets-spam-assassin');
3
+
4
+ const data = corpus();
5
+ let csvData = "text,is_spam\n";
6
+
7
+
8
+ function cleanText(str) {
9
+ if (str.startsWith('""') && str.endsWith('""')) str = str.substring(2, str.length - 2)
10
+ else if (str.startsWith('"') && str.endsWith('"')) str = str.substring(1, str.length - 1)
11
+ str = str.replace(/["]/g, '""')
12
+ if (str.includes('\n') || str.includes(',') || str.includes(`""`)) str = '"' + str + '"'
13
+ return str
14
+ }
15
+
16
+
17
+ for (let i = 0; i < data.length; i++) {
18
+ const text = data[i].text;
19
+ const group = data[i].group;
20
+ let isSpam = 0;
21
+ if (group.includes('spam')) {
22
+ isSpam = 1;
23
+ }
24
+ csvData += cleanText(text) + ',' + isSpam + '\n';
25
+ }
26
+
27
+ fs.writeFile('spam_data.csv', csvData, (err) => {
28
+ if (err) throw err;
29
+ console.log('CSV file saved!');
30
+ });
spam_assassin.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ special = []
4
+ df = pd.read_csv('spam_data.csv')
5
+
6
+ for index, row in df.iterrows():
7
+ text = row['text']
8
+
9
+ if text is not None and text != '' and 'Subject: ' in text:
10
+ subject = text.split("""
11
+ Subject: """)[1]
12
+
13
+ if '\n' in subject:
14
+ subject = subject.split("\n")[0].strip()
15
+ elif '\r' in subject:
16
+ subject = subject.split("\r")[0].strip()
17
+ else:
18
+ raise Exception('No newline found in subject: ' + str(text))
19
+ content = text.split("""
20
+
21
+ """)[1:]
22
+ content = """
23
+
24
+ """.join(content)
25
+
26
+ text = subject + """
27
+
28
+ """ + content
29
+
30
+ df.at[index, 'text'] = text
31
+ else:
32
+ special.append({'text': text, 'is_spam': row['is_spam']})
33
+
34
+ df.to_csv('spam_data_clean.csv', index=False)
35
+ pd.DataFrame(special).to_csv('special.csv', index=False)