Skip to content

Commit aead633

Browse files
committed
Add logging for generation() and refine code
It is another part of work of issue #15, following commit 33e4693. Some code is refined for higher efficiency.
1 parent 33e4693 commit aead633

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

auto_comment_plus.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,14 @@ def generation(pname, _class=0, _type=1, opts=None):
8585
items = ['商品名']
8686
items.clear()
8787
items.append(pname)
88-
for item in items:
88+
opts['logger'].debug('Items: %s', items)
89+
loop_times = len(items)
90+
opts['logger'].debug('Total loop times: %d', loop_times)
91+
for i, item in enumerate(items):
92+
opts['logger'].debug('Loop: %d / %d', i + 1, loop_times)
93+
opts['logger'].debug('Current item: %s', item)
8994
spider = jdspider.JDSpider(item)
95+
opts['logger'].debug('Successfully created a JDSpider instance')
9096
# 增加对增值服务的评价鉴别
9197
if "赠品" in pname or "非实物" in pname or "增值服务" in pname:
9298
result = ["赠品挺好的。",
@@ -97,27 +103,30 @@ def generation(pname, _class=0, _type=1, opts=None):
97103
]
98104
else:
99105
result = spider.getData(4, 3) # 这里可以自己改
106+
opts['logger'].debug('Result: %s', result)
100107

101108
# class 0是评价 1是提取id
102109
try:
103110
name = jieba.analyse.textrank(pname, topK=5, allowPOS='n')[0]
104-
except Exception as _:
111+
opts['logger'].debug('Name: %s', name)
112+
except Exception as e:
113+
opts['logger'].warning(
114+
'jieba textrank analysis error: %s, name fallback to "宝贝"', e)
105115
name = "宝贝"
106116
if _class == 1:
117+
opts['logger'].debug('_class is 1. Directly return name')
107118
return name
108119
else:
109-
comments = ''
110120
if _type == 1:
111121
num = 6
112122
elif _type == 0:
113123
num = 4
114-
if len(result) < num:
115-
num = len(result)
116-
else:
117-
num = num
118-
for i in range(num):
119-
comments = comments + \
120-
result.pop(random.randint(0, len(result) - 1))
124+
num = min(num, len(result))
125+
# use `.join()` to improve efficiency
126+
comments = ''.join(random.sample(result, num))
127+
opts['logger'].debug('_type: %d', _type)
128+
opts['logger'].debug('num: %d', num)
129+
opts['logger'].debug('Raw comments: %s', comments)
121130

122131
return 5, comments.replace("$", name)
123132

0 commit comments

Comments
 (0)