Make Python 3 actually work
dblume

dblume commited on 2024-07-26 09:18:32
Showing 2 changed files, with 17 additions and 29 deletions.

... ...
@@ -76,9 +76,9 @@ def calculate_median_mean_stddev(time_blocks):
76 76
         count = len(block)
77 77
         median = 0.0
78 78
         if count % 2:
79
-            median = float(block[count/2])
79
+            median = float(block[count//2])
80 80
         elif count > 0:
81
-            median = (block[count / 2 - 1] + block[count / 2]) / 2.0
81
+            median = (block[count // 2 - 1] + block[count // 2]) / 2.0
82 82
 
83 83
         # Calculate the mean and standard deviation
84 84
         if count > 0:
... ...
@@ -101,7 +101,7 @@ def process_feed(yaml_items, metric, metric_times):
101 101
         wday = time.localtime(time_posted).tm_wday
102 102
         value_times = i[metric_times]
103 103
         values = i[metric]
104
-        value_times_indices = [(t - time_posted) / 1800 for t in value_times]
104
+        value_times_indices = [(t - time_posted) // 1800 for t in value_times]
105 105
         for j in range(len(values)):
106 106
             if value_times_indices[j] > 7 or value_times_indices[j] < 0:
107 107
                 continue
... ...
@@ -119,15 +119,6 @@ even_watermark = "E0E0FF"
119 119
 odd_watermark = "D0D0F0"
120 120
 
121 121
 
122
-def asciiize(s):
123
-    try:
124
-        return s.encode('ascii')
125
-    except UnicodeEncodeError:
126
-        return s
127
-    except exceptions.AttributeError:
128
-        return s
129
-
130
-
131 122
 def send_email(subject, message, toaddrs,
132 123
         fromaddr='"%s" <%s>' % (os.path.basename(__file__), smtp_creds.user)):
133 124
     """ Sends Email """
... ...
@@ -252,8 +243,6 @@ def process_feed(yaml_items):
252 243
                 yaml_items.pop()
253 244
 
254 245
             for i in yaml_items:
255
-                # i['title'] = asciiize(i['title'])
256
-                # i['tags'] = map(asciiize, i['tags'])
257 246
                 process_yaml_item(i)
258 247
 
259 248
     else:
... ...
@@ -298,7 +287,7 @@ def process_item(feed_item, yaml_items):
298 287
     elif hasattr(feed_item, 'date_parsed'):
299 288
         date_parsed = feed_item.date_parsed
300 289
     else:
301
-        print("process_item found no timestamp for", asciiize(feed_item.link))
290
+        print("process_item found no timestamp for", feed_item.link)
302 291
     timecode_parsed = calendar.timegm(date_parsed)
303 292
 
304 293
     link = feed_item.link
... ...
@@ -319,11 +308,11 @@ def process_item(feed_item, yaml_items):
319 308
     if yaml_item is None:
320 309
         author = ''
321 310
         if hasattr(feed_item, 'author'):
322
-            author = asciiize(feed_item.author)
311
+            author = feed_item.author
323 312
 
324 313
         # Make a new yaml_item
325
-        yaml_item = {'title'               : asciiize(feed_item.title),
326
-                     'link'                : asciiize(link),
314
+        yaml_item = {'title'               : feed_item.title,
315
+                     'link'                : link,
327 316
                      'author'              : author,
328 317
                      'tags'                : [],
329 318
                      'orig_posted'         : timecode_parsed,
... ...
@@ -337,7 +326,7 @@ def process_item(feed_item, yaml_items):
337 326
                     }
338 327
         if hasattr(feed_item, 'tags'):
339 328
             for i in feed_item.tags:
340
-                yaml_item['tags'].append(asciiize(i.term))
329
+                yaml_item['tags'].append(i.term)
341 330
 
342 331
         yaml_items.insert(0, yaml_item)
343 332
         any_entry_added = True
... ...
@@ -393,8 +382,6 @@ def Get_fb_stats(url_string):
393 382
     comments = -1
394 383
     likes = -1
395 384
 
396
-    url_string = url_string.encode('utf-8')
397
-
398 385
     try:
399 386
         encoded = urllib.parse.urlencode({'access_token': facebook_token})
400 387
         url = 'https://graph.facebook.com/v2.11/?id=%s&fields=engagement&%s'
... ...
@@ -473,9 +460,9 @@ def make_index_html(yaml_items, weekend_stats, weekday_stats):
473 460
             f.write('<tr valign="center" class="%s">\n  <td><strong><a href="%s">%s</a></strong> <span class="date">at %s</span> <span class="author">by %s</span></td>\n' % \
474 461
                      (image_index % 2 and "even" or "odd",
475 462
                       image['link'],
476
-                      image['title'].encode('ascii', 'xmlcharrefreplace'),
477
-                      time.strftime("%H:%M", time.localtime(image['orig_posted'])).encode('ascii', 'xmlcharrefreplace'),
478
-                      image['author'].encode('ascii', 'xmlcharrefreplace'),
463
+                      image['title'],
464
+                      time.strftime("%H:%M", time.localtime(image['orig_posted'])),
465
+                      image['author'],
479 466
                      )
480 467
                    )
481 468
             f.write('  <td>%s<td>\n' % (image['qualified'] != -1 and '<img src="star_30.png" width="30" height="29" />' or ''))
... ...
@@ -489,15 +476,15 @@ def make_index_html(yaml_items, weekend_stats, weekday_stats):
489 476
 
490 477
 def make_feed_file(yaml_items):
491 478
     """Writes the RSS feed file with the YAML items."""
492
-    with codecs.open(os.path.join(localdir, 'rss_feed.xml'), 'wb', 'utf-8') as f:
479
+    with codecs.open(os.path.join(localdir, 'rss_feed.xml'), 'w', 'utf-8') as f:
493 480
         f.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n<channel>\n<atom:link href=\"http://techcrunch.dlma.com/rss_feed.xml\" rel=\"self\" type=\"application/rss+xml\"/>\n<title>Trending at TechCrunch</title><link>http://techcrunch.dlma.com</link>")
494 481
         f.write("<pubDate>%s</pubDate><description>Automatically Generated Feed</description><language>en-us</language>\n" % (time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())))
495 482
         count = 0
496 483
         for item in yaml_items:
497 484
             now = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(item['orig_posted']))
498 485
             if item['qualified'] != -1:
499
-                escaped_title = html.escape(item['title']).encode('ascii', 'xmlcharrefreplace')
500
-                escaped_author = html.escape(item['author']).encode('ascii', 'xmlcharrefreplace')
486
+                escaped_title = html.escape(item['title'])
487
+                escaped_author = html.escape(item['author'])
501 488
                 f.write("<item><title>%s</title><pubDate>%s</pubDate><link>%s</link><guid isPermaLink=\"false\">%s</guid><description><![CDATA[By: %s]]></description></item>\n" % \
502 489
                          (escaped_title, now, item['link'], item['link'], escaped_author))
503 490
                 count += 1
... ...
@@ -537,7 +524,7 @@ if __name__=='__main__':
537 524
         #
538 525
         yaml_fullpath = os.path.join(localdir, 'techcrunch.yaml')
539 526
         if os.path.exists(yaml_fullpath):
540
-            with open(yaml_fullpath, 'rb') as f:
527
+            with open(yaml_fullpath, 'r') as f:
541 528
                 items = yaml.load(f, Loader=yaml.Loader)
542 529
                 if items is None:
543 530
                     print(yaml_fullpath, "exists, but was empty.")
... ...
@@ -545,6 +532,7 @@ if __name__=='__main__':
545 532
 
546 533
                 # Do any dictionary item updating that might be necessary
547 534
 #                for item in items:
535
+#                    item['link'] = str(item['link'])
548 536
 #                    if not item.has_key('fb_shares'):
549 537
 #                        item['fb_shares'] = []
550 538
         else:
... ...
@@ -600,7 +588,7 @@ if __name__=='__main__':
600 588
 
601 589
             # For the one file we really use, write to a file on the side, then move it.
602 590
             yaml_newfile_fullpath = os.path.join(localdir, 'techcrunch_temp_writable.yaml')
603
-            with open(yaml_newfile_fullpath, 'wb') as f:
591
+            with open(yaml_newfile_fullpath, 'w') as f:
604 592
                 yaml.dump(items, f, default_flow_style=None, width=120)
605 593
             try:
606 594
                 os.rename(yaml_newfile_fullpath, yaml_fullpath)
607 595