Question

Below is my code which queries Facebook.

I wanted to restrict the total size of the actual message to being 980 varchar.

    def write_csv(fname, rows, header=None, append=False, **kwargs):
    filemode = 'ab' if append else 'wb'
    with open(fname, filemode) as outf:
        out_csv = csv.writer(outf, **kwargs)
        if header:
            out_csv.writerow(header)
        out_csv.writerows(rows)

def main():
    ts = FacebookSearch()
    data = ts.search('appliance')
    js = json.loads(data)

    messages = ([msg['created_time'], msg.get('message', 'Key "message" is not present.').replace('\n', '').encode('utf8'),  msg['from']['id']] for msg in js.get('data', []))
    #def messages(s, l):  ## breaks here
        #return s if len(s)<=l else s[0:l-3]+'...'  ## Breaks here



    write_csv('fb_washerdryer.csv', messages, append=True)


if __name__ == '__main__':
    main()

I attempted above to define it within my function but I got this error:

Traceback (most recent call last):
  File "./facebook_washer_dryer8.sh", line 52, in <module>
    main()
  File "./facebook_washer_dryer8.sh", line 48, in main
    write_csv('fb_washerdryer.csv', messages, append=True)
  File "./facebook_washer_dryer8.sh", line 35, in write_csv
    out_csv.writerows(rows)
TypeError: writerows() argument must be iterable

I thought I was doing the right thing but now I am bit confused.

Was it helpful?

Solution

I think this is what you want:

...
#Create the shortening function
def short_message(s, l): 
        #return s if len(s)<=l else s[0:l-3]+'...'  
#define a variable to be shortened if too long
mess = msg.get('message', 'Key "message" is not present.').replace('\n', '').encode('utf8')
#pass the shortened message
write_csv('fb_washerdryer.csv', short_message(mess, 980), append=True)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top