-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordCount.py
79 lines (70 loc) · 2.4 KB
/
wordCount.py
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
#!/usr/bin/env python
# getDiaries.py: extract diaries from questionaires in tactus file
# usage: getDiaries.py file
# 20191111 erikt(at)xs4all.nl
import csv
import gzip
import re
import sys
import xml.etree.ElementTree as ET
MESSAGES = "./Messages/Message"
ID = "PatientId"
DATE = "DateSent"
SENDER = "Sender"
BODY = "Body"
SUBJECT = "Subject"
WORDCOUNT = "WordCount"
CLIENT = "CLIENT"
TOTAL = "Total"
YES = "yes"
FIELDNAMES = [ID,DATE,SENDER,WORDCOUNT,TOTAL]
def cleanupText(text):
if text == None: return("")
text = re.sub(r"\s+"," ",text)
text = re.sub(r"^ ","",text)
text = re.sub(r" $","",text)
return(text)
def makeId(fileName):
thisId = re.sub(r".*/","",fileName)
thisId = re.sub(r"\.xml.*$","",thisId)
return(thisId)
def initData(thisId):
data = { ID:thisId}
for fieldName in FIELDNAMES:
if fieldName != ID: data[fieldName] = ""
return(data)
def wordCount(text):
return(len(text.split()))
def main(argv):
with sys.stdout as csvFile:
csvWriter = csv.DictWriter(csvFile,fieldnames=FIELDNAMES)
csvWriter.writeheader()
for inFileName in argv[1:]:
inFile = gzip.open(inFileName,"rb")
inFileContent = inFile.read()
inFile.close()
root = ET.fromstring(inFileContent)
thisId = makeId(inFileName)
clientTotal = 0
for message in root.findall(MESSAGES):
data = initData(thisId)
wordCountBody,wordCountSubject = 0,0
for element in message:
if element.tag == DATE: data[DATE] = cleanupText(element.text)
elif element.tag == SENDER: data[SENDER] = cleanupText(element.text)
elif element.tag == SUBJECT:
wordCountSubject = wordCount(cleanupText(element.text))
elif element.tag == BODY:
wordCountBody = wordCount(cleanupText(element.text))
data[WORDCOUNT] = wordCountSubject+wordCountBody
if SENDER in data and data[SENDER] == CLIENT:
clientTotal += data[WORDCOUNT]
csvWriter.writerow(data)
data = initData(thisId)
data[SENDER] = CLIENT
data[TOTAL] = YES
data[WORDCOUNT] = clientTotal
csvWriter.writerow(data)
if __name__ == "__main__":
sys.exit(main(sys.argv))
exit(0)