-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdf-parser-detainer-warrants.R
147 lines (128 loc) · 2.01 KB
/
pdf-parser-detainer-warrants.R
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
# Set up working directory
setwd("~")
setwd("Detainer-Warrant-PDF-Parser/input")
# Load required libraries
library(pdftools)
library(stringr)
library(data.table)
library(jsonlite)
library(dplyr)
# List all files within a directory
filenames =
list.files()
# Read in each PDF into a list
datalist =
lapply(
filenames,
function(x){
pdftools::pdf_text(x)
}
)
# Unlist the object
datalist =
unlist(
datalist
)
# Format the object as a dataframe
df =
lapply(
datalist,
function(x){
data.frame(
matrix(
unlist(x),
nrow =
length(x),
byrow = TRUE
)
)
}
)
# Convert to "pretty" JSON
df2 =
jsonlite::toJSON(
df,
auto_unbox = TRUE,
pretty = TRUE
)
# Extract all IDs (strings that end with "DT")
unique_ids =
stringr::str_extract_all(
df2,
".{6}DT"
)
# Unlist and convert to vector
unique_ids =
as.vector(
unlist(
unique_ids
)
)
# Remove any instance of 'n' before the id"
unique_ids =
gsub(
"n",
"",
unique_ids
)
# # Split the text into vectors using `DT`
df3 =
str_split(
df2,
"DT"
)
# Remove the first vector from the list object
df3 =
df3[[1]][-1]
# Extract Zip Codes
df4 =
lapply(
df3,
function(x){
str_extract(
x,
"TN \\d{5}"
)
}
)
# Unlist zip_codes
zip_codes =
unlist(
df4
)
# Remove "TN " from zipcodes
zip_codes =
gsub(
"TN ",
"",
zip_codes
)
# Extract dates
dates =
str_extract(
df3,
"\\d+/\\d+/\\d+"
)
# Create a dataframe out of all three variables
warrants =
data.frame(
unique_ids,
zip_codes,
dates
)
# Remove duplicated detainer warrants
warrants =
warrants[
!duplicated(
warrants$unique_ids
),
]
# Write out results to a CSV
setwd("~")
setwd("Detainer-Warrant-PDF-Parser/output")
write.csv(
warrants,
"detainer-warrants.csv",
row.names =
FALSE
)