CommentProcessor.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. def process_comment(res_data):
  2. result = {}
  3. def add_comment(root, father_user_id, user_id, comment):
  4. if father_user_id in root.keys():
  5. root[father_user_id]['comments'][user_id] = comment
  6. return root
  7. for key in root.keys():
  8. comments = root[key]['comments']
  9. new_comments = add_comment(
  10. comments, father_user_id, user_id, comment)
  11. if new_comments:
  12. root[key]['comments'] = new_comments
  13. return root
  14. return False
  15. for data in res_data:
  16. comment_id = data['id']
  17. host_user_id = data['user']['screen_name']
  18. if '//' in data['text_raw']:
  19. texts = data['text_raw'].split('//')
  20. father_id = ''
  21. for text in texts[::-1]:
  22. text = text.split(':')
  23. if len(text) == 1:
  24. content = text[0] if text[0] == '' else '快转微博'
  25. if father_id == '':
  26. result[host_user_id] = {
  27. 'comment_id': comment_id, 'content': content, 'comments': {}
  28. }
  29. else:
  30. result = add_comment(result, father_id, host_user_id, {
  31. 'content': content,
  32. 'comment_id': comment_id,
  33. 'comments': {}
  34. })
  35. else:
  36. user_id = text[0][1:]
  37. content = text[1] if text[1] != '' else '快转微博'
  38. if father_id == '':
  39. if user_id not in result.keys():
  40. result[user_id] = {
  41. 'content': content,
  42. 'comments': {}
  43. }
  44. father_id = user_id
  45. else:
  46. result = add_comment(result, father_id, user_id, {
  47. 'content': content,
  48. 'comments': {}
  49. })
  50. father_id = user_id
  51. else:
  52. content = data['text_raw']
  53. result[host_user_id] = {
  54. 'comment_id': comment_id, 'content': content, 'comments': {}
  55. }
  56. return result