1_data_preparation.ipynb 4.39 KB
Newer Older
Philipp Koncar's avatar
Philipp Koncar committed
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "import glob"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configuration\n",
    "*input_dir:* The path to the directory that contains your text files. Please make sure to use a '/' (slash) in the end. For example: `path/to/texts/`.\n",
    "\n",
    "*dataframe_filename:* The filename for the resulting pandas DataFrame. You may use the **.p** extension indicating a pickled file, but you are free to use whatever you like. Just make sure this is consistent in the subsequent sentiment analysis step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_dir = \"\"\n",
    "dataframe_filename = \"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Directory Setup (Optional)\n",
    "Creates directories according to the configuration if not already created manually."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if not os.path.exists(input_dir):\n",
    "    os.makedirs(input_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Preparation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load texts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_file_names = glob.glob(\"{}*.txt\".format(input_dir))\n",
    "print(\"found {} texts\".format(len(text_file_names)))\n",
    "texts = []\n",
    "for text_file_name in text_file_names:\n",
    "    if \"\\\\\" in text_file_name:\n",
    "        corrected_filename = text_file_name.split(\"\\\\\")[-1]\n",
    "    elif \"/\" in text_file_name:\n",
    "        corrected_filename = text_file_name.split(\"/\")[-1]\n",
    "    with open(text_file_name, \"r\", encoding=\"utf-8\") as input_file:\n",
    "        texts.append([corrected_filename, input_file.read()])\n",
    "print(\"loaded {} texts\".format(len(texts)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"searching files for attributes and text\")\n",
    "prepared_texts = []\n",
    "num_attributes = 0\n",
    "for filename, text in texts:\n",
    "    lines = text.split(\"\\n\")\n",
    "    prepared_text = {\"filename\": filename}\n",
    "    cur_line = 0\n",
    "    for line in lines:\n",
    "        line_type, line_content = line.split(\"=\")[:2]\n",
    "        if line_type != \"text\":\n",
    "            try:\n",
    "                line_content = float(line_content)\n",
    "            except ValueError:\n",
    "                pass\n",
    "            prepared_text.update({line_type: line_content})\n",
    "        else:\n",
    "            break\n",
    "        cur_line += 1\n",
    "    num_attributes = max(num_attributes, cur_line)\n",
    "    prepared_text.update({\"text\": \" \".join(lines[cur_line:])[5:]})\n",
    "    prepared_texts.append(prepared_text)\n",
    "\n",
    "print(\"found {} additional attributes in .txt files\".format(num_attributes))\n",
    "\n",
    "texts_df = pd.DataFrame(prepared_texts)\n",
    "texts_df.set_index(\"filename\", inplace=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "texts_df.to_pickle(dataframe_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}