I am setting up a project which involves a lot of data analysis, each data point represented by a line in a large text file. In order to test for certain types of data, I added a tag to each line (It needs to remain in one file, though). Now I want to conveniently choose which type of data I want to include, currently I have five types (positive
, negative
, neutral
, objective
, objective-OR-neutral
). Coming from C, I wrote my parse(filename)
function the following way:
# parsing.py
# flags
POS = 1
NEG = 2
NEU = 4
OBJ = 8
OON = 16
# 'flag transformation dictionary'
ftd = {u'positive': POS,
u'negative': NEG,
u'neutral': NEU,
u'objective': OBJ,
u'objective-OR-neutral': OON}
# Read flagged data from file, return only entries with the right flag.
# Each line is: <flag><\t><content>
def parse(f_loc, flags=0):
for line in open(f_loc):
flag, content = line.strip().split('\t')
if ftd[flag] & flags: # this wouldn't be as pretty with kwargs
yield content
Using this utility function somewhere else would then look like this:
# parsing_test.py
from parsing import parse, POS, NEG, NEU, OBJ, OON
# print all data flagged as 'positive', 'negative', or 'neutral'
for entry in parse('file.txt', POS | NEG | NEU):
print(entry)
# print all data, no matter the flag
for entry in parse('file.txt', POS | NEG | NEU | OBJ | OON):
print(entry)
I am just starting this project and am very conscious about good style (especially intuitiveness, extendability, robustness, and speed), so I would appreciate any criticism.