def get_count():
comments = Comment.query.all()
for comment in comments:
for word in comment.parsed.split('/'):
if word in pos_list:
comment.pos_count += 1
elif word in neg_list:
comment.neg_count += 1
elif '80' <= word and word <= '99':
comment.pos_count += 1
elif '0' <= word and word < '80':
comment.neg_count += 1
db.session.add(comment)
print "Comment %04d counted!" % comment.id
db.session.commit()
print "ALL DONE!"
python类Comment()的实例源码
def get_theta():
import math
theta = [0.0, 0.0, 0.0]
step = 0.01
comments = Comment.query.all()[:100]
print "Comments gotten! Training..."
for m in range(1000):
for comment in comments:
if comment.emotion != -1:
x = [1, float(comment.pos_count), float(comment.neg_count)]
feature_sum = 0
for i in range(3):
feature_sum += theta[i]*x[i]
h = 1 / (1+math.e**-(feature_sum))
for i in range(3):
theta[i] = theta[i] + step*(comment.emotion-h)*x[i]
print "Theta Gotten: ", theta
def get_emotion():
print "Calculating thetas..."
get_theta()
print "Done!"
comments = Comment.query.filter_by(emotion=-1).all()
for comment in comments:
x = [1, float(comment.pos_count), float(comment.neg_count)]
hypothesis = 0
feature_sum = 0
for i in range(3):
feature_sum += theta[i]*x[i]
hypothesis = 1 / (1+math.e**-(feature_sum))
if 0 < hypothesis < 0.4:
comment.analysis_score = 0
elif 0.4 <= hypothesis < 0.6:
comment.analysis_score = 0.5
elif 0.6 <= hypothesis < 1:
comment.analysis_score = 1
def add(book_id):
form = CommentForm()
the_book = Book.query.get_or_404(book_id)
if the_book.hidden and not current_user.is_administrator():
abort(404)
if form.validate_on_submit():
the_comment = Comment(user=current_user, book=the_book, comment=form.comment.data)
db.session.add(the_comment)
db.session.commit()
flash(u'???????', 'success')
return redirect(request.args.get('next') or url_for('book.detail', book_id=book_id))
def delete(comment_id):
the_comment = Comment.query.get_or_404(comment_id)
if current_user.id == the_comment.user_id or current_user.can(Permission.DELETE_OTHERS_COMMENT):
the_comment.deleted = 1
book_id = the_comment.book_id
db.session.add(the_comment)
db.session.commit()
flash(u'????????.', 'info')
return redirect(request.args.get('next') or url_for('book.detail', book_id=book_id))
else:
abort(403)
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
Permission=Permission, Post=Post, Comment=Comment)
def get_queryset(self):
parent = self.get_parent()
queryset = models.Comment.objects.filter(
timeslot__order__parent=parent).order_by('id')
return queryset
def get_evaluation_avg_score(self, teacher: models.Teacher):
# ??????
avg_score = models.Comment.objects.filter(
timeslot__order__teacher=teacher,
timeslot__order__status=models.Order.PAID,
).aggregate(Avg("score"))
return avg_score["score__avg"] or 0
def get_bad_comment(self, teacher: models.Teacher):
# ?????
return models.Comment.objects.filter(
timeslot__order__teacher=teacher,
timeslot__order__status=models.Order.PAID,
score__lt=3,
).count()
def _my_evaluation_badge(self):
# ?????????
# ?????
return models.Comment.objects.filter(
web_visited=False,
timeslot__order__teacher=self.teacher,
timeslot__order__status=models.Order.PAID,
).count()
# my_evaluation = None
# return my_evaluation
def count_comment(self, comment: models.Comment):
self.all_count += 1
self.sum_score += comment.score
if comment.is_high_praise():
self.good_count += 1
if comment.is_mediu_evaluation():
self.mid_count += 1
if comment.is_bad_comment():
self.bad_count += 1
def handle(self, *args, **options):
for order in models.Order.objects.all():
for timeslot in order.timeslot_set.filter(comment__isnull=True):
fake_comment = models.Comment()
fake_comment.score = timeslot.id % 5 + 1
fake_comment.content = "fake comment {id}".format(id=timeslot.id)
fake_comment.save()
timeslot.comment = fake_comment
timeslot.save()
def make_shell_context():
"""??????"""
return dict(
app = app,
db = db,
User = User,
Role = Role,
Comment = Comment
)
def parse():
"""parse the comments"""
import jieba
import jieba.posseg as pseg
# Load User's Dictionary
path_list = os.getcwd().split('/')
path_list.append("dict.txt")
dict_path = '/'.join(path_list)
jieba.load_userdict(dict_path)
# Disimss These Flags
dismiss = ['b', 'c', 'r', 'uj', 'u', 'p', 'q', 'uz', 't', 'ul', 'k', 'f',
'ud', 'ug', 'uv']
comments = Comment.query.all()
for comment in comments:
word_list = []
pseg_cut = pseg.cut(comment.body)
for word, flag in pseg_cut:
if flag not in dismiss:
word_list.append(word)
comment.parsed = '/'.join(word_list)
db.session.add(comment)
print "Comment %04d Parsed!" % comment.id
db.session.commit()
print "ALL DONE!"
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
Permission=Permission, Post=Post, Comment=Comment)
def make_shell_context():
return dict(db=db, User=User, Follow=Follow, Role=Role,
Permission=Permission, Post=Post, Comment=Comment)
def make_shell_context():
return dict(app=app, db=db, User=User, Good=Good, CommentObj=Comment(), Comment=Comment)
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role, Permission=Permission,
Post=Post, Comment=Comment)
def clear_all_tables():
db_session.query(EventHook).delete()
db_session.query(FrontPage).delete()
db_session.query(SubredditPage).delete()
db_session.query(Subreddit).delete()
db_session.query(Post).delete()
db_session.query(User).delete()
db_session.query(ModAction).delete()
db_session.query(Comment).delete()
db_session.commit()
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role, Permission=Permission, Post=Post, Comment=Comment)
def post(self):
"""????(???)"""
form = request.form
mid = form.get('movieId', '')
movie = Movie.query.get(mid)
if movie is None:
return {'message': '?????'}, 233
try:
rating = int(form.get('rating', ''))
if rating < 0 or rating > 5:
return {'message': '????'}, 233
except ValueError:
return {'message': '????'}, 233
content = form.get('content', '').strip()
if len(content) == 0:
return {'message': '????????'}, 233
comment = Comment()
comment.id = UUID()
comment.rating = rating
comment.content = content
comment.movieId = mid
comment.username = current_user.id
db.session.add(comment)
total = movie.ratingNum * movie.rating
movie.ratingNum += 1
movie.rating = (total + rating) / movie.ratingNum
db.session.commit()
return {'message': '????', 'id': comment.id}, 200
def get(self, id):
"""??????"""
comment = Comment.query.get(id)
if comment is None:
return {'message': '?????'}, 233
return comment.__json__(), 200
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Category=Category, Comment=Comment, Post=Post, Lable=Lable)
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
Permission=Permission, Post=Post, Comment=Comment)
def api_post_and_get_comment(blog_id):
'''
post a new comment
'''
if not g.__user__:
return make_response('Please login', 403)
content = request.form.get('content').lstrip('\n').rstrip()
if not content:
return make_response('Content cannot be empty.')
# create a new Comment and save it to mongodb
blog = db.blogs.find_one({'_id': ObjectId(blog_id)})
comment = Comment(
blog_id = blog_id,
blog_author = blog.get('user_name'),
blog_title = blog.get('title'),
user_id = g.__user__.get('_id'),
user_name = g.__user__.get('name'),
user_image = g.__user__.get('image'),
content = content
)
comments = []
for document in db.comments.find({'blog_id':blog_id}).sort("created", -1):
document.update(_id=str(document['_id']))
document.update(content=markdown_filter(document['content']))
if document.get('subcomment'):
for subcomment in document.get('subcontent'):
subcomment.update(content=markdown_filter(subcomment['content']))
comments.append(document)
return jsonify(comments=comments)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Follow = Follow,
Permission=Permission, Post=Post, Comment=Comment, Category=Category)
def forged():
from forgery_py import basic, lorem_ipsum, name, internet, date
from random import randint
db.drop_all()
db.create_all()
Role.seed()
guests = Role.query.first()
def generate_comment(func_author, func_post):
return Comment(body=lorem_ipsum.paragraphs(),
created=date.date(past=True),
author=func_author(),
post=func_post())
def generate_post(func_author):
return Post(title=lorem_ipsum.title(),
body=lorem_ipsum.paragraphs(),
created=date.date(),
author=func_author())
def generate_user():
return User(name=internet.user_name(),
email=internet.email_address(),
password=basic.text(6, at_least=6, spaces=False),
role=guests)
users = [generate_user() for i in range(0, 5)]
db.session.add_all(users)
random_user = lambda: users[randint(0, 4)]
posts = [generate_post(random_user) for i in range(0, randint(50, 200))]
db.session.add_all(posts)
random_post = lambda: posts[randint(0, len(posts) - 1)]
comments = [generate_comment(random_user, random_post) for i in range(0, randint(2, 100))]
db.session.add_all(comments)
db.session.commit()