Created
May 24, 2014 15:06
-
-
Save crawsible/d6bdab8a5ce9efdd55e2 to your computer and use it in GitHub Desktop.
A little command-line tool to run through a CSV of post titles and identify which of them are people looking to buy an item.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/local/bin/python3 | |
import sys | |
import csv | |
BUYER_CONSTANTS = ('WTB', 'Wtb', 'WANTED', 'Wanted', 'wanted', 'LOOKING FOR', | |
'Looking for', 'looking for', 'TO BUY', 'to buy') | |
class TitleParser(object): | |
def __init__(self, titles): | |
self.titles = titles | |
self._parse_buyers() | |
def _parse_buyers(self): | |
print('Parsing buyers...') | |
buyer_checklist = [] | |
for title in self.titles: | |
buyer = any([i in title for i in BUYER_CONSTANTS]) | |
if buyer: | |
buyer_checklist.append('YES') | |
else: | |
buyer_checklist.append('NO') | |
self.buyer_checklist = buyer_checklist | |
print('Checklist complete--there were %s buyers!' | |
% (self.buyer_count())) | |
def buyer_count(self): | |
count = 0 | |
for check in self.buyer_checklist: | |
if check == 'YES': count += 1 #flake8: noqa | |
return count | |
def main(): | |
if len(sys.argv) < 2: | |
print('\nWhoops--the script requires an argument! Plese use: \n\n' | |
'\tpath/to/the/titleparser.py path/to/the/csv_file.csv\n\n' | |
'to specify the .csv file to be parsed.\n') | |
sys.exit(1) | |
try: | |
with open(sys.argv[1], 'rt', encoding='utf-8') as csvfile: | |
reader_object = csv.reader(csvfile, delimiter='φ', quotechar='ɣ') | |
row_list = [] | |
csv_size = 0 | |
for row in reader_object: # "row" not yet list object | |
row_list.append(row) # a list of 1-element list objects | |
csv_size += 1 | |
except IOError: | |
print("\nSorry, but there seems to be something wrong with the file " | |
"passed as the argument! Please make sure:\n\n" | |
"\t1. it's a .csv file (with a .csv prefix),\n" | |
"\t2. you have the requisite permissions to read it, and\n" | |
"\t3. you're pointing to the right filepath/in the right " | |
"working directory.\n") | |
sys.exit(1) | |
print(csv_size) | |
titles = [(''.join(i)+'') for i in row_list] | |
title_parser = TitleParser(titles) | |
print(len(title_parser.titles), 'titles') | |
new_filename = sys.argv[1][:-4] + '-buyers.csv' | |
with open(new_filename, 'w+', encoding='utf-8', | |
newline='') as new_csvfile: | |
writer_object = csv.writer(new_csvfile, delimiter='`', | |
quotechar='|') | |
for i in title_parser.buyer_checklist: | |
writer_object.writerow([i]) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment