Пример #1
0
def wordseg(method):
    cfg_path = os.path.expanduser(u'~/.nomadic')
    # Open the config file.
    with open(cfg_path, 'r') as cfg_file:
        user_cfg = json.load(cfg_file)
        config.update(user_cfg)

    notepath = config['root']

    #testnote = str(notepath + '/wdxtub.md')

    h = codecs.open(testnote, 'r', 'utf-8')
    text = h.read()


    if method == 1:
        seg_list = jieba.cut(text, cut_all=False)
        fh = codecs.open('./seg/test.txt', 'w', 'utf-8')
        fh.write(' '.join(seg_list))
        tags = jieba.analyse.extract_tags(text, topK=10)
        print(",".join(tags))
    elif method == 2:
        s = SnowNLP(text)

        for w in s.keywords(10):
            print w.encode('utf-8')

        for su in s.summary(3):
            print su.encode('utf-8')

    print 'done'
Пример #2
0
def Spider_zhihu(sentence):
    sentence = urllib2.quote(sentence)
    url  = 'http://www.zhihu.com/search?q='
    finalUrl = url + sentence + '&type=question'
    webpage = urllib2.urlopen(finalUrl)
    text = webpage.read()
    soup = BeautifulSoup(text)
    website = soup.findAll(attrs = {'class' :"question_link"})[0]
    print website
    postfix = website['href']
    result = 'http://www.zhihu.com'
    finalresult = result + postfix
    resultpage = urllib2.urlopen(finalresult)
    text = resultpage.read()
    result_soup = BeautifulSoup(text)
    readable_text = result_soup.findAll(attrs = {'data-action' :'/answer/content'})[0]
    #readable_text = readable_text[1:]
    print readable_text
    preprocess = ''
    for line in readable_text:
        for sub_line in str(line).split('。'):
            preprocess = preprocess + sub_line + '\n'
    text = strip_tags(preprocess)
    print text
    text = SnowNLP(text)
    summary_text = ''
    for line in text.summary(3):
        summary_text = summary_text + line+'\n'
    print summary_text
    return summary_text
Пример #3
0
 def search_word(self):
     """
     from doc_queue search author article and store
     """
     while not self.doc_queue.empty():
         print "runing thread is %s" % threading.current_thread().getName()
         arti_url,arti_title = self.doc_queue.get().keys()[0]
         #get aritcle and store in file
         try:
             soup = BeautifulSoup(urllib2.urlopen("http://"+self.index_url+arti_url).read())
         except urllib2.HTTPError:
             self.max_doc_num+=1
             continue
         data = soup.find('meta',{'name':'author'})
         data = data['content'].encode('utf-8')
         author =  {'d':data}
         author_enc = urllib.urlencode(author)[2:]
         lead_div = soup.find('div',{"class":"atl-main"})
         text = lead_div.find('div',{'class':'bbs-content clearfix'}).get_text().strip().encode('utf-8')+"\r\n"
         text = unicode(text.decode('utf-8'))
         s = SnowNLP(text)
         fp = open("%s/%s.txt"%(self.folder,arti_title),"a")
         fp.write("title:%s\r\n"%arti_title.encode("utf-8"))
         fp.write("URL:%s\r\n"%arti_url.encode("utf-8"))
         fp.write("data:%s"%text.encode('utf-8'))
         fp.write("keywords:")
         for key in s.keywords(5):
             fp.write(key.encode('utf-8')+" ")
         fp.flush()
         fp.close()
         """store file
Пример #4
0
def Spider_how(sentence):
    sentence = urllib2.quote(sentence)
    url  = 'http://jingyan.baidu.com/search?word='
    finalUrl = url + sentence
    webpage = urllib2.urlopen(finalUrl)
    text = webpage.read()
    soup = BeautifulSoup(text)
    website = soup.findAll(log = "type:1000,pos:search_result,num:1")[0]
    postfix = website['href']
    result = 'http://jingyan.baidu.com'
    finalresult = result + postfix
    resultpage = urllib2.urlopen(finalresult)
    text = resultpage.read()
    result_soup = BeautifulSoup(text)
    readable_text = result_soup.findAll('p')
    readable_text = readable_text[1:]
    preprocess = ''
    for line in readable_text:
        for sub_line in str(line).split('。'):
            preprocess = preprocess + sub_line + '\n'
    text = strip_tags(preprocess)
    print text
    text = SnowNLP(text)
    summary_text = ''
    for line in text.summary(3):
        summary_text = summary_text + line+'\n'
    print summary_text
    return summary_text
Пример #5
0
 def _tweet_to_feature(self, tweetlist):
     f = numpy.zeros(len(self.featuretable),dtype=numpy.float64)
     for tweet in tweetlist:
         s = SnowNLP(tweet)
         s = SnowNLP(s.han)
         keys = s.keywords(3)
         for wd in keys:
             if self.featuretable.has_key(wd):
                 f[self.featuretable[wd]-1]+=1
     return f/numpy.sqrt(numpy.dot(f,f))
Пример #6
0
def keywords():
    countnumber = readWeiboData.count()[0]
    for i in range(1,countnumber):
        textdata = readWeiboData.getText(i)
        # textdata = str(textdata).split('http')[0:-1]
        text = str(textdata).decode('utf8')
        text = SnowNLP(text)
        texttosql = ''
        for j in range(0,len(text.keywords(3))):
            texttosql+=text.keywords(3)[j]+" "

        writeWeiboData.keywordsWriteToSql(texttosql,i)
Пример #7
0
def main(options):
    print("text")
    text = strip_tags(get_text(options))
    print(text)

    s = SnowNLP(text)
    print("Summary:")
    for summary in s.summary(3):
        print(summary)
    print("Keywords:")
    for keyword in s.keywords():
        print(keyword)
 def GetNewsUrlSummary(self,newsUrl):
     newsTextNodeSoup = self.GetNewsTextNodeSoup(newsUrl)
     newsText = " ".join(map(lambda node : node.get_text(),newsTextNodeSoup))
     try:
         newsText = unicode(newsText)
     except:
         pass
     snow = SnowNLP(newsText)
     summaryList = snow.summary(3)
     map(lambda aPieceSummary:(len(aPieceSummary) > self.MaxSummaryLen) and summaryList.remove(aPieceSummary),summaryList)
     summaryText = " ".join(summaryList)
     if len(summaryText) > self.MaxSummaryLen:
         summaryText = summaryText[0:self.MaxSummaryLen]
     return summaryText
Пример #9
0
 def get(self, article_sid, type):
     args = parser.parse_args()
     if type == 'extract':
         article = self.db.get('select title,content from article where sid=%s', (article_sid,))
         s = SnowNLP(article['content'])
         keywords = s.keywords()
         abstract = s.summary()
         keywords = ','.join(keywords)
         abstract = ','.join(abstract)
         self.db.update('update article set keywords=%s,abstract=%s,processed=1 where sid=%s',
                        (keywords, abstract, article_sid))
         return {
             'sid': article_sid,
             'keywords': keywords,
             'abstract': abstract
         }
Пример #10
0
def jsonFunc():
    f = file('test.json')
    source = f.read()
    result = json.loads(source)

    if not result.has_key('answer'):
      return u'对不起我找不到呢'.encode('utf-8')
    elif len(result['answer']['text'].encode('utf-8')) <= 100:
      return result['answer']['text'].encode('utf-8')
    elif len(result['answer']['text'].encode('utf-8')) > 100:
      original = result['answer']['text'].encode('utf-8').replace('。','\n')
      text = SnowNLP(original)
      summary_text = ''
      for line in text.summary(3):
        summary_text = summary_text + line + u'。'.encode('utf-8')
      print summary_text
      return summary_text
Пример #11
0
def Spider_what(sentence):
    sentence = urllib2.quote(sentence)
    url = 'http://zh.wikipedia.org/wiki/'
    finalUrl = url + sentence
    webpage = urllib2.urlopen(finalUrl)
    text = webpage.read()
    soup = BeautifulSoup(text)
    readable_text = soup.findAll('p')
    preprocess = ''
    for line in readable_text:
        for sub_line in str(line).split('。'):
            preprocess = preprocess + sub_line + '\n'
    #readable_text = str(readable_text)[1:-1]
    #preprocess = unicode(preprocess,'utf-8').encode('utf-8')
    text = strip_tags(preprocess) 
    text = SnowNLP(text)
    summary_text = ''
    for line in text.summary(1):
        summary_text = summary_text + line + '\n'
    
    print summary_text
    return summary_text
Пример #12
0
 def trainfeature(self, filepath):
     featuretable = {}
     (utf8_encoder, utf8_decoder, utf8_reader, utf8_writer) = codecs.lookup('utf-8')
     fd = utf8_reader(open(filepath))
     tweetlist = fd.readlines()
     fd.close()
     VALID_EXP = ur'([A-Za-z\u4e00-\u9fa5]+)'
     VALID_REGEX = re.compile(VALID_EXP)
     for tweet in tweetlist:
         s=SnowNLP(tweet)
         s=SnowNLP(s.han)
         keys = s.keywords(3)
         for wd in keys:
             mtch = VALID_REGEX.search(wd)
             if mtch is None:
                 continue
             else:
                 wd = mtch.group(0)
             if featuretable.has_key(wd):
                 continue
             else:
                 featuretable[wd]=len(featuretable)+1
     if len(featuretable):
         self.featuretable = featuretable
Пример #13
0
    encoding='utf-8')
result[1] = open(
    r"C:\Users\I321338\PycharmProjects\Segmentation\Demo_Result_type2.txt",
    'w',
    encoding='utf-8')
result[2] = open(
    r"C:\Users\I321338\PycharmProjects\Segmentation\Demo_Result_type3.txt",
    'w',
    encoding='utf-8')
result[3] = open(
    r"C:\Users\I321338\PycharmProjects\Segmentation\Demo_Result_other.txt",
    'w',
    encoding='utf-8')
text = f.readline()
while text != "":
    text_snow = SnowNLP(text)
    score = text_snow.sentiments
    if score < 0.4:
        flag = True
        for index, val in enumerate(typ):
            seg_list = jieba.cut(text, cut_all=False)
            for j in seg_list:
                if (j in val) and (j != ' '):
                    result[index].write(str(score) + ' ' + text)
                    flag = False
                    break
        if flag:
            result[3].write(text)
        #r.write(text)
    text = f.readline()
f.close()
Пример #14
0
def get_sentiment(word):
    text = u'{}'.format(word)
    s = SnowNLP(text)
    print(s.sentiments)
def fetch_weibo_data(keyword, start_time, end_time, page_id, page_num):
    """
    根据关键字,起止时间以及页面id进行数据爬取, 返回由[dict…]构成
    """

    mycookie = ""
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
        "cookie": mycookie}

    resp = requests.get(url_template.format(keyword, start_time, end_time, page_id), headers=headers, allow_redirects=True)

    print("微薄url:", resp.url)
    if resp.status_code == 200:
        print("fetch_data爬取状态正常")
    else:
        print("爬取状态异常:", resp.status_code)

    if not resp.raise_for_status():
        print("网页请求无报错")  # 网页请求报错
    else:
        print("网页请求出错:", resp.raise_for_status())
        print("网页请求历史", resp.history)

    soup = BeautifulSoup(resp.text, 'lxml')
    all_contents = soup.select('.card-wrap')                 # card-feed为微博内容
    print("本页微博条数:", len(all_contents))

    wb_count = 0
    mblog = []  # 保存处理过的微博
    for z, card in enumerate(all_contents):
        try:
            mid_in = card.get('mid')
        except:
            break
        if (mid_in is not None):  # 如果微博ID不为空则开始抓取
            wb_username = card.select_one('.txt').get('nick-name')  # 微博用户
            href = card.select_one('.from').select_one('a').get('href')
            re_href = re.compile('.*com/(.*)/.*')
            wb_userid = re_href.findall(href)[0]  # 微博用户ID
            if len(card.select(".txt")) == 2:
                wb_content = card.select('.txt')[1].text.strip()  # 长篇微博会有<展开全文>
            else:
                wb_content = card.select('.txt')[0].text.strip()  # 微博全文内容
            wb_content = wb_content.replace(" ", "")              # 剔除空格
            wb_place = []

            if len(card.select(".txt")) == 2:
                tag_a = card.select('.txt')[1].select("a")        # 获取所有的a标签,组成list
                if tag_a:
                    for i in range(len(tag_a)):
                        text = tag_a[i].text.strip()

                        if "·" in text:
                            wb_place.append(text[1:])
                else:
                    wb_place = []
            else:
                tag_a = card.select('.txt')[0].select("a")
                if tag_a:
                    for i in range(len(tag_a)):
                        text = tag_a[i].text.strip()

                        if "·" in text:
                            wb_place.append(text[1:])
                else:
                    wb_place = []
            wb_create = card.select_one('.from').select_one('a').text.strip()  # 微博创建时间
            wb_url = 'https:' + str(card.select_one('.from').select_one('a').get('href'))  # 微博来源URL
            wb_id = str(card.select_one('.from').select_one('a').get('href')).split('/')[-1].split('?')[0]  # 微博ID
            wb_createtime = time_process(wb_create)
            wb_forward = str(card.select_one('.card-act').select('li')[1].text)  # 微博转发
            wb_forwardnum = num_process(wb_forward.strip())                      # 微博转发数
            wb_comment = str(card.select_one('.card-act').select('li')[2].text)  # 微博评论
            wb_commentnum = num_process(wb_comment)                              # 微博评论数
            wb_like = str(card.select_one('.card-act').select_one('em').text)    # 微博点赞数
            try:
                wb_mood = SnowNLP(wb_content).sentiments
            except:
                print("can't be 0")

            if (wb_like == ''):  # 点赞数的处理
                wb_likenum = '0'
            else:
                wb_likenum = wb_like

            blog = {'wb_id': wb_id,  # 生成一条微博记录的列表
                    'wb_username': wb_username,
                    'wb_userid': wb_userid,
                    'wb_content': wb_content,
                    'wb_createtime': wb_createtime,
                    'wb_forwardnum': wb_forwardnum,         # 转发数
                    'wb_commentnum': wb_commentnum,         # 评论数
                    'wb_likenum': wb_likenum,
                    'wb_url': wb_url,
                    'wb_place': wb_place,
                    'wb_mood': wb_mood
                    }
            mblog.append(blog)
            wb_count = wb_count + 1  # 表示此页的微博数
    print("正在爬取" + str(start_time) + "----第"+ str(page_id)+"页/共" + str(page_num) + "页 ---- 当前页微博数:" + str(wb_count))
    return mblog
Пример #16
0
                print(BEN)
                M.add(BEN)

    if content == "4":
        print("想要笨笨先开始还是你先开始呢?笨笨先开始输入0,你先开始输入1")
        who = int(input())
        if who == 0 or who == 1:
            idiom_start(who)
        else:
            print("笨笨不知道你在说什么呀")

    # 情感倾诉模块
    if content == "5":
        print("笨笨来啦,今天过得怎么样呀")
        content = input()
        s = SnowNLP(content)

        # 划分句子
        a = []
        for sentence in s.sentences:
            score = SnowNLP(sentence).sentiments
            print(score)
            a.append(score)

        average = np.mean(a)
        print(average)

        number = random.sample(range(1, 6), 1)
        m = [str(i) for i in number]
        index = int("".join(m))
        workbook = xlrd.open_workbook("情感分析回应模板.xlsx")
Пример #17
0
        dict[i] = dict[i] + 1
    else:
        dict[i] = 1

high = []
count = 0
for i in sorted(dict.items(), key=operator.itemgetter(1), reverse=True):
    if len(i[0]) >= 2 and count < 10:
        high.append(i[0])
        count = count + 1
    if count >= 10:
        break
print(high)  # 10个关键词
f2 = open('tyfResult.txt', 'w', encoding="utf-8")
for i in high:
    f2.write(i)
    f2.write(' ')

# 对分词后的文本生成
# font = r'C:\\Windows\\fonts\\SourceHanSansCN-Regular.otf'

# my_wordcloud = WordCloud().generate(wl_space_split)
#
# my_wordcloud.to_file("cloudpic.jpg")

s = SnowNLP(text)
print(u"\n输出关键句子:")
for k in s.summary(1):
    print(k)
    f2.write(k)
f2.close()
Пример #18
0
f_string = f.read()
f.close()
text = unicode(f_string, 'utf-8')
print(isinstance(text, unicode))

from snownlp import normal
from snownlp import seg
from snownlp.summary import textrank
from snownlp import SnowNLP




if __name__ == '__main__':

    s = SnowNLP(text)
    print(s.keywords(3))
    print(s.summary(3))
    
    t = normal.zh2hans(text)
    sents = normal.get_sentences(t)
    doc = []
    for sent in sents:
        words = seg.seg(sent)
        words = normal.filter_stop(words)
        doc.append(words)
    rank = textrank.TextRank(doc)
    rank.solve()
    for index in rank.top_index(5):
        print(sents[index])
    keyword_rank = textrank.KeywordTextRank(doc)
Пример #19
0
print('/'.join(all_comment_seg[388]))


# ## 情感分析
        情感分析实际上是二元分类的推演,通过概率来判断给定样本的概率大小,随后设定阈值,超过此阈值则给出判断,在本案例中,情感分析实际上有某种预示,五星好评和一星差评的情感倾向一定是不同的,这也是进行情感判断的出发点.
# In[21]:


from snownlp import SnowNLP #加载snownlp


# In[22]:


#test
s = SnowNLP(T_3_comment.题目[1])


# In[23]:


s.words #词


# In[26]:


s.tags #词性标注


# In[27]:
Пример #20
0
from snownlp import normal
from snownlp import seg
from snownlp.summary import textrank
from snownlp import SnowNLP


if __name__ == '__main__':
    '''
    t = normal.zh2hans(text)
    sents = normal.get_sentences(t)
    doc = []
    for sent in sents:
        words = seg.seg(sent)
        words = normal.filter_stop(words)
        doc.append(words)
    rank = textrank.TextRank(doc)
    rank.solve()
    for index in rank.top_index(5):
        print(sents[index])
    keyword_rank = textrank.KeywordTextRank(doc)
    keyword_rank.solve()
    for w in keyword_rank.top_index(5):
        print(w)
    '''
    text = u'#菇morning#看到这个热门我的第一反应是 '
    s = SnowNLP(text.encode('utf-8'))
    keywords = s.keywords(10)
    for each in keywords:
        print(each)
    tmp = s.sentiments
    print(tmp)
Пример #21
0
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 05 15:11:29 2015

@author: mongolia19
"""
#from pyteaser import SummarizeUrl
#url = "http://en.wikipedia.org/wiki/Automatic_summarization"
#summaries = SummarizeUrl(url)
#print summaries
from snownlp import SnowNLP
import FileUtils
passage = FileUtils.OpenFileGBK('./reading/passage.txt')
passage = passage.encode("UTF-8")
s = SnowNLP(passage)
print s.keywords(5)
print s.summary(1)
Пример #22
0
# coding: utf-8
from snownlp import SnowNLP
a = SnowNLP(u'墨头号毒枭逃亡期间密会zhong国老牌影帝')
print(len(u'人民币对美元汇率中间价继续下跌10个基点(2014-12-23 10:23:06)_...'))
b = a.sim(u'人社部要求停发美甲师职业资格证|美甲师|人社部_新浪财经_新浪网')
print(b)
Пример #23
0
__author__ = 'Luolin'
#-*-encoding:utf-8-*-
from snownlp import SnowNLP

text = u'''
很久没有写文章了,但是回想起这几年坎坷的奋斗路程,其中的酸甜苦辣,血泪交加,值得整理成文字,纪念我们即将逝去的青春。同时希望正在惆怅的年轻人们,看了我的奋斗历程,能收获微薄的安慰和鼓励,仅此而已。  08年的金融海啸,把很多人推向了失业和破产的潮流,无数人在这一年输的心惊胆战,如今提起尚有不寒而栗的感觉。而那年我们大四,步入了东奔西跑的求职路,几乎所有人都碰的头破血流、皮青脸肿的回来,我也不例外。直至09年初,整个专业签约的寥寥无几,对于一所历史悠久的985工程大学来说,是前所未有的。  09年春节还未过完,我就背着沉甸甸的精神包袱,踏上了艰辛的求职之路,这是一条看不到目标和方向的路。火车是站票到上海的,全程27小时,人山人海,几乎透不过气来。从火车上下来那一刻,站的浮肿的脚踏在真实的地面上,酥麻无力,走起路来东摇西摆的,不过呼吸到新鲜的空气,有一种重获新生的舒适感。但是这种舒适的感觉转瞬即逝,想起此行的目的,又有一种坠入地狱深渊的痛楚。借宿在上海理工大学的学生宿舍里,很感激当时收留我的朋友,农和西瓜,也很感谢那个时候认识的兄弟,良。  顶着凛冽的寒风,一会虹口,一会闸北闵行,大大小小的招聘会,都出现我狼狈的身影,奔波劳累一个月之后,终于在虹口一个小招聘会上,找到了一份要求是高中毕业的业务员工作,工资1800,不包吃住,没有其他补贴,工作地点在杨浦区。接着又匆匆忙忙的赶回学校,赶着写毕业论文,赶着毕业答辩。就在即将毕业的时候,谈了四年的女朋友和我分手了,她保送的是上海交大的研究生,这也是当初我选择上海的原因,当时也犹豫要不要放弃上海的工作,南回广深,但是最终还是选择继续上海行,因为答应过的事情要做到。
文章会慢慢的上来跟大家分享,平时工作比较忙,我一般会晚上更新.毕业的分离,依然是那么不舍,男的女的都哭的稀里哗啦。我走的晚,送走一个又一个,那种离别的伤痛,总似尖刀,一次又一次的在心上雕刻着他们每个人的名字,列车远去的时候,泪水模糊了视线。我离开的时候,整个宿舍楼都是空荡荡的了,记得很清楚来给我送行的人,也记得很清楚我在列车上给我打电话送别的每个人,但是没有她。09年7月初我从学校直接到了上海,开始了我更加艰辛的奋斗历程,当我步入这个我人生中第一次任职的公司(以下简称A公司)的时候,满含着期待和紧张,认真的审视着公司的每一个人。
@人生下站见2012 3楼 2013-12-27 23:14:44  楼主,我看着呢,继续呀!我是12年毕业的那你是刚刚步入社会一年半,也应该是事业开始上升的时期了。加油!一个刚毕业的,没有任何工作经验的人,一开始做的更多是打杂的事情,公司很小,就几个人,我每天会早一会到公司,先打扫收拾一遍,一直坚持几个月,直至公司来了几个新人。而业务上的事情没人带,没人教,自己拿着公司的资料了解产品,几天之后,经理就给我下达约客户的任务,于是我拿着公司提供的名册,开始了电话营销的工作。刚开始的时候,连按号码的手都是发抖的,颤颤巍巍,战战兢兢的,电话接通那一刻,之前自己拟好的对话语句忘的干干净净,对面喂喂的声音震耳发聩,只好硬着头皮,磕磕绊绊的说了几句,对方听的不耐烦,啪一声挂掉了电话。这啪的一声似乎震伤了心,回想当时的心灵是那么脆弱,又是那么卑微,相信每个做业务的人,都有经历过那一幕,有的人或许因为打击放弃了,如果你选定了业务这个工作,那么不过再多坎坷,也要坚持。我拿起电话,继续拨通了下一个号码,继续着听到许多啪啪的声音,一次一次的撞击着心灵。那天我打了100个电话,却没有约到一个客户,那种无望,那种黑暗,让人看不到光明,感受到的只是7月夏季里的冰冷,接受着公司领导的批评。好不容易熬到了下班,逃一般的跑出公司,买了几瓶啤酒,在一个人少的小公园,独自喝着,看着这个繁华无比的城市,却没有一点点的归属感,一股强烈的悲伤感。半夜,拖着半醉的身体,回到那个住着七八个人的一室一厅房子,我们过着轮流着睡床上或打地铺的日子,对于我那微薄1800工资来说,上海的房租太高了,而离开了学校,我就坚决不会向家里要钱,而且还有两个弟弟在上大学。
连续拨打几天电话之后,终于有一天约到了客户,连续如此,后来一个东北的大哥聊的还可以,毕竟在东北上了四年学,有些许话题,最后这个大哥在一个项目上试用了我们的产品,说如果这次试用效果好的话,以后就都用我们的产品。这是我工作以来第一个客户,我一直小心翼翼的,只是没想到试用的产品,都问题不断,最终客户就做死了,后来也很不好意思去见这个东北大哥。其实真正的业务能手,是能够拉回这个客户的,当时的我,意识不到所有公司的产品都有可能存在这样那样的问题,重点是一定要帮客户解决,所以就没继续跟进客户。后来认识一位年纪比较大的师傅,姓金,我在深圳他还给我来过电话,鼓励我。当时金师傅虽然没有买我们的产品,因为他们做的是政府项目,使用的产品都是选定的,但是他一直鼓励我,让我在这个冰冷的世界里,看到了希望。在公司还是认识了一位终生的朋友,一名华工的博士,进,无论硬件软件都是一流的高手,掌握着智能视频方面的核心算法,我们经常下班了一起喝低档的红酒,他当时买房买车,压力很大。就这样在A公司10个月时间,后来一直没什么业绩,总觉得自己很没脸面继续下去,在2010年的4月辞职,买了到桂林的火车票,这是我毕业以来第一次旅游,弟弟在那边上学,他带我在桂林玩了几天,接着回家玩了半个月,见了几个兄弟,理了理思路。
2010年过了五一,我就整理行装,开始了深圳之旅,这个以速度著称的城市,让我充满好奇,也让我的人生开始了新的篇章。匆匆忙忙的面试,最后选了一家做手机屏幕和镜头的F公司,依然是业务员,底薪低的不愿意说,只是当时深圳的最低工资水平。上班的第一天,我就跟着经理去K公司送样品,这是我们公司第一次与K公司接触,这家上市公司在国内外都是赫赫有名的,我和经理都非常紧张。门卫拨通了我们仅认识的一位吴采购的电话,确认过之后才让我们进K公司的大门,在偌大的一个园区中找到了吴采购的办公楼区。吴采购很忙,几乎没有正眼看过我们,经理说我们是F公司,过来贵司送样品的,吴采购哦了一声之后说我现在有事情,你们把样品送到5栋6楼张工那里去测试吧,然后就不见人影了,经理说要去见客户,也离开了,剩下我一个人经过了层层询问之后,才找到了张工,和他简单聊了几句,我说我第一天来上班的,好不容易才找到这里,他则说这里太大,你能找到算是不错,怪不得你们公司那么放心你一个新人来跟我们的项目。听到这里有点欣慰,其实他对我的评价不是因为我能找到他这里,是因为我一个新人就能来跟K公司那么大的项目,而只有我自己才清楚,是没人愿意来跟K公司,因为觉得没希望,经理也是被迫于老板的指令才来的。
昨晚被灌醉了,现在还难受。这几天感冒了,难受啊,还没来得及写下来更新,sorry。K公司因为没有成单的希望,经理非常迅捷的把K公司的跟进任务甩给了我,像甩了个巨大的包袱。我是一个实诚的人,哪怕同事们都议论K公司不可能,让我别费心思,应付一下就好,我还是坚持每天去K公司拜访,了解项目的进展情况。或许因为我经常出现,或许又因为我实在不浮夸滑头,张工对我就不那么陌生了,有时候会跟我聊聊天,说的都是一些工作上的事情:都是些K公司制度严格,要求高,做个项目一但超出预算,奖金就打水漂,又问我们待遇情况怎么样。我呢,则是话少的人,听多说少,因为怕说多了出错。样品测试的效果稍微差了一些,以致项目一直没什么进展,K公司当时已经决定使用另外一家供应商X公司的产品,他们之间一直有合作。直到有一天,我在K公司等张工的时候,他从会议室出来,唠叨的说了一句:整机成本怎么会超出1块钱呢,哎!我则敏锐的接收到了这句话的所有信息:K公司这个项目整机成本要求100元人民币以下,而这次会议核算出来的成本是101,也就意味着按照目前的计划做下去的话,整个项目组的奖金都会泡汤。我们的价格比X公司的便宜0.5元,样品测试的效果其实和X公司的差不了多少,我为什么不借这个超出预算的机会导入我们的产品呢?于是我幽幽的对张工说:整机客户要求挺高,还要成本控制在100以下,真的挺难的,现在这些配件都是大批量采购的价格,降几分钱都困难啊。张工:是啊,愁啊,折腾了两个多月了,原本以为这个项目就这样完美收官了呢,谁知道这时候出现成本超出问题。我:客户要求真的很严格吗?您上次测试我们的产品效果和X公司对比差很多吗?张工:其实没什么差别,只是说一直和X公司合作,组里的人不愿意轻易换,担心换了没保障。我:既然效果差不多,我们的比X公司的便宜0.5元,我再想办法找老板谈谈,让他平本接这个单,估计能腾出来1块钱空间。张工:这个很难吧,不赚钱的生意你们老板会做吗?再则,组里的人我怎么说服他们。我:客户主要是看效果,您用我们的产品装出整机让客户看,如果客户接受了,你们的成本又能降下来1块钱,我相信这个是大家都很乐意接受的事情。价格上我会帮您想办法的。张工:那好吧,你明天再带10个你们的样品过来,我试试装整机给客户看效果。我:没问题。
帮你顶,人还是厚道点好恩呢,厚道的人走的远~@confidencel 13楼 2014-01-06 15:31:54  身体是革命的本钱,修养好继续啊,期待着。。。你写的很好!谢谢,我工作之余写的!
第二天我领了样品一大早给张工送过去,他看到我带着样品来,知道我昨天答应他的事情搞定了,就兴致勃勃的带着我去项目技术主管那:李工,这个是F公司的小郑,这是他们的产品,你测试一下,然后让人装整机明天带给迪拜客户看效果。李工:好的,先放这,我一会测试。我:李工,您好,麻烦您尽快测试一下,这样你们的客户能尽早看效果确认,那么这个项目也能早些完成。李工:那好,我现在就测试,你留个名片给我,有什么事情我联系你。在这里分享一点,客户说先放着,我一会有空了测试的时候,一定要追着客户让他测试,因为你不知道他接下来会不会有空,或者有空了会不会想起来去测试,又或者根本不想测试,切记。我把新的报价单给了张工,他也在上面潇洒的签了字,然后让我拿给采购。
去送样品之前还有一段小故事:从K公司出来,突然觉得深圳的空气质量不错,深呼吸了几下,立马赶回公司,经理不在,又事关紧急,我直接杀到了老板办公室:杨总,我是小郑,关于K公司的事我想跟您谈谈。杨总:小郑,你刚来公司的吧,怎么K公司是你在跟?这边坐。我:是的,经理忙,让我来跟。杨总:哦,那你说说K公司那边的进展。我:K公司的这个项目本来已经决定了用X的产品,但是出现了一个问题,他们整机成本超出预算1块钱。杨总:既然决定了,那还有什么希望呢,成本才超出1块钱,对于他们这样的大公司来说是没什么问题的。我:多1块少1块对K公司本身是没什么影响,但是对这个项目组的每个人影响很大,K公司有个规定,成本超出预算,项目组所有奖金取消。杨总:哦,还有这个规定啊,这是让整个项目组的人为公司想尽办法降低成本啊,K公司就是高明。那现在你想怎么做?我:我们的产品效果是和X公司差不多,报价上比他们低0.5元,我想着我们索性再降0.5元,帮他们解决成本问题,那么他们肯定会用我们的产品。虽然价格上比我们预期的少0.5元,但是我们不需要花钱请客送红包等其他交际费用了,再加上市面上元件成本在下降,我们一旦与K公司合作成功,一开始可能没什么利润,但是慢慢就会带来利润空间的,而且我们又帮了他们,取得信任之后,我们还可以与K公司合作其他项目,这是一个难得的机会。杨总沉思了一下说:小郑你在哪里上的学,什么专业的?我:在东北大学,学的是工商管理市场营销专业。杨总:哦,难怪,想法不错,就按照你说的办,你从新拟个报价单,我来签字,以后整个公司为你开直通车,关于K公司的事情,你可以直接来找我。我:谢谢杨总,客户还需要10个样品,我明天带给他们。杨总拿来个单签了字递给我:多领两个给他们备用。我:好的。
我拿着有张工签字的报价单,找到了采购部吴采购的位置,恰巧他不在那,于是我问他旁边位置的同事:您好,请问吴先生不在吗?他说:吴工今天请假了,你有事么事吗?我:我是F公司的,这是项目部张工让我给吴先生的报价单。他接着说:那你放吴工桌上吧,明天他来了能看到。我思索了一下,假如就放在桌子上,这里是大办公室,经常有同行的人来来往往拜访,如果他们看到了,价格透露了不说,万一同行把我的报价单偷偷拿走了,那到时候采购部拿不到报价审核部下来就麻烦了,于是我说:张工说了,事情很急,要我今天一定交上去给采购部审核。他答道:这样啊,那你去右边第二间办公室找采购薛主管吧。我:谢谢您。咚咚咚,我敲了三下门,里面传出声音:进来。我推开门,这不大不小的办公司布置很简约,一张深色办公桌,几张椅子,一个一幅将近两米宽的山水国画,上面有草书题字,我也是喜爱国画书法的人,于是不禁夸了一句:山峦层层相叠,流水潺潺延绵,字体粗狂有力,好画好字。薛主管说到:你也是喜欢国粹的人啊。我赶忙说:薛主管,不好意思,光欣赏您的书画,忘了自我介绍了,我是F公司的小郑,这里有一个报价单是项目部张工让我交给您的审核的。薛主管接着说:哈哈,现在年纪轻轻的,没几个像你这样还喜欢书画了,来来,坐。我一边坐下,一边把有张工签字的报价单交给薛主管,顺带了一张名片。薛主管边看边说:这个产品之前不是选定了X公司的吗,老张之前也签了字的,怎么突然改了呢。我想着他们公司内部的事情不能乱说,就假装不知道的说:我也不清楚,有一次张工开完会跟我说让我再做个新报价单的,还送样测试。薛主管拿起电话:老张,这个项目之前不是决定用X公司的产品吗?怎么还让其他公司报价?也不知道张工说了什么,一会薛主管说:那好吧,但是样品你们可要测试好,毕竟以前没合作过。挂了电话之后,薛主管对我说:小郑,张工挺看好你们的产品啊,不过咱们之前没合作过,即使项目部那边测试结果通过了,我们采购部和品质部还要对你们公司进一步审查,通过之后才能获得我们公司合格供应商的资格,这个是公司有明文规定的。我:那贵司需要哪些审查呢?薛主管:企业注册年限、注册资金、合作过的企业这些都需要,但主要是审厂。我听得有点迷糊,审厂又审哪些方面呢,想问又不敢再问了。
'''

s = SnowNLP(text)


for word in s.keywords(10):   # [u'语言', u'自然', u'计算机']
    print word

for sum in  s.summary(3):
    print sum

Пример #24
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-	


from snownlp import SnowNLP

s = SnowNLP(u':#微感动#【一次搀扶,四载照顾[心]】路遇一摔倒老人蜷缩在地,她将老人扶起送回家。不放心老人她次日再去拜访,得知老人孤身一人后从此义务照顾!每天看望,帮洗衣服,陪着聊天…她坚持至今4年!她说当下好多人不敢扶老人,想用行动改变大家看法!31岁山西籍好人赵艳善心无畏惧[赞](央视记者杨晓东)')

print '中文分词:'
for each in s.words:
	print each,
print '\n'

print '词性标注:'
for each in s.tags:
	print "('" + each[0] + "','" + each[1] + "')"
print '\n'

print '拼音:'
for each in s.pinyin:
	print each,
print '\n'

print '提取文本关键字:'
for each in s.keywords(3):
	print each,
print '\n'

print '提取文本摘要:'
for each in s.summary(3):
	print each
Пример #25
0
def data_crawl(dbname):
    client = pymongo.MongoClient('127.0.0.1', 27017)  # 缺少一步骤进行属性的清洗操作,确定是否有这个值
    db = client.goverment
    start_url = 'http://liuyan.cjn.cn/threads/content?tid={id}'
    header = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'
    }
    count_num = 1
    #111132断点抓取100001
    for i in range(100001, 300001):
        tmp = start_url.format(id=i)
        print(tmp)

        try:
            req = requests.get(tmp, headers=header, timeout=(3, 7))
            if req.status_code == 500:
                pass
            elif req.status_code == 200:
                selector = etree.HTML(req.content)

                name = selector.xpath(
                    '/html/body/div[6]/h2/b/text()')[0].strip()

                condition = '/html/body/div[6]/h2/b/em/text()'  #记得消除空格
                condition = selector.xpath(condition)[0].strip()

                content = '//*[@id="zoom"]/text()'
                content = selector.xpath(content)[0]

                problem_time = '/html/body/div[6]/h3/span/text()'
                problem_time = selector.xpath(problem_time)[0][-16:]

                problem_cluster = '/html/body/div[6]/h3/em/a/text()'  #有多个
                problem_cluster = selector.xpath(problem_cluster)

                problem_cluster_list = problem_cluster
                new_tmp = ''
                for tmp in problem_cluster:
                    new_tmp += tmp + ','  #逗号分隔
                problem_cluster = new_tmp

                try:
                    unit = '/html/body/div[7]/ul/li/h3/em/text()'  #只有一个,两个一样的xpath,需要字符串处理

                    ss = selector.xpath(unit)[0]
                    split_ss = ss.split('\n                            \n')

                    unit = split_ss[0].strip()[5:]
                    reply_time = split_ss[1].strip()

                    reply_content = '/html/body/div[7]/ul/li/p/text()'
                    reply_content = ' '.join(selector.xpath(reply_content))

                    data = {
                        '标题': name,
                        '回复状态': condition,
                        '内容': content,
                        '问题时间': problem_time,
                        '问题分类': problem_cluster,
                        '问题分类列表': problem_cluster_list,
                        '政府机构': unit,
                        '回复时间': reply_time,
                        '回复内容': reply_content
                    }
                except:
                    data = {
                        '标题': name,
                        '回复状态': condition,
                        '内容': content,
                        '问题时间': problem_time,
                        '问题分类': problem_cluster,
                        '问题分类列表': problem_cluster_list,
                        '政府机构': '',
                        '回复时间': '',
                        '回复内容': ''
                    }
                ##添加情感分析模块
                s = SnowNLP(content)
                rates = s.sentiments
                if (rates >= 0.5):
                    data['情感'] = '积极'

                elif (rates < 0.5):
                    data['情感'] = '消极'

                db[dbname].insert_one(data)
                print('插入一条' + str(count_num))
                count_num += 1
        except Exception as e:
            time.sleep(1)
            print("未知错误", e)
Пример #26
0
from common.persistence import from_pickle, to_pickle
from common.html_util import strip_tags

pos_dict = from_pickle('pos_norm.pkl')
print '%d positions' % len(pos_dict)
pid = 403932
assert pid in pos_dict
for p in pos_dict[pid]:
    print p

# get keywords of pos
print 'jieba tags'
pos = pos_dict[pid]
import jieba.analyse

tags = jieba.analyse.extract_tags(pos[2])
for t in tags:
    print t

print 'snow tags'
from snownlp import SnowNLP
s = SnowNLP(pos[2])
for t in s.keywords(limit=20):
    print t
def analyseSignature(friends):
    signatures = ''
    emotions = []
    pattern = re.compile("1f\d.+")
    for friend in friends:
        signature = friend['Signature'].encode('utf-8')
        # print signature
        if(signature != None):
            signature = signature.strip().replace('span', '').replace('class', '').replace('emoji', '')
            signature = re.sub(r'1f(\d.+)','',signature)
            if(len(signature)>0):
                nlp = SnowNLP(signature.decode('utf-8'))
                emotions.append(nlp.sentiments)
                print signature
                print nlp.sentiments
                print emotions

                signatures += ' '.join(jieba.analyse.extract_tags(signature,5))
    with open('signatures.txt','w') as file:
        signatures = signatures.encode('utf-8')
        file.write(signatures)

    print emotions

    # Sinature WordCloud
    back_coloring = np.array(Image.open('flower.jpg'))
    wordcloud = WordCloud(
        font_path='D:\python\project\ichatpro\simfang.ttf',
        background_color="white",
        max_words=2000,
        mask=back_coloring,
        max_font_size=75,
        random_state=45,
        width=960,
        height=720,
        scale=2,
        margin=15
    )

    wordcloud.generate(signatures.decode("utf-8"))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
    wordcloud.to_file('signatures.jpg')


    # Signature Emotional Judgment
    count_good = len(list(filter(lambda x:x>0.66,emotions)))
    count_normal = len(list(filter(lambda x:x>=0.33 and x<=0.66,emotions)))
    count_bad = len(list(filter(lambda x:x<0.33,emotions)))
    print count_bad
    print count_normal
    print count_good



    labels = [u'负面消极',u'中性',u'正面积极']
    values = (count_bad,count_normal,count_good)
    plt.rcParams['font.sans-serif'] = ['simHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.xlabel(u'情感判断')
    plt.ylabel(u'频数')
    plt.xticks(range(3),labels)
    plt.legend(loc='upper right',)
    plt.bar(range(3), values, color = 'rgb')
    plt.title(u'%s的微信好友签名信息情感分析' % friends[0]['NickName'])
    plt.show()
Пример #28
0
def keywords(text,num):
	s = SnowNLP(text.decode('utf8'))
	#st = frequency.Stopwords()
	return s.keywords(num)
Пример #29
0
cursor = conn.cursor()

for file in files:
    txt_path = path + file

    # 读取txt文件
    f = open(txt_path, 'r')
    text = f.readlines()

    count = len(text)
    f.close()
    sentences = []
    senti_score = []
    a = 0
    for i in text:
        a1 = SnowNLP(i.decode('utf-8'))
        a2 = a1.sentiments
        sentences.append(i)  # 语序...
        senti_score.append(a2)
        a = a + a2
    table = pd.DataFrame(sentences, senti_score)
    x = [i for i in range(1, count + 1)]

    name = file.split(".")[0]
    count = len(x)
    score = a / len(x)
    pl.mpl.rcParams['font.sans-serif'] = ['SimHei']
    cm = pl.cm.get_cmap('Dark2')
    # cm = pl.cm.get_cmap('Set1')
    # cm = pl.cm.get_cmap('Set2')
    sc = pl.scatter(x=x, y=senti_score, c=senti_score, s=7, cmap=cm)
Пример #30
0
#!/usr/bin/python3
# coding: utf-8
# pip install snownlp
# SnowNLP 是一个 python 写的类库, 可以方便的处理中文文本内容, 是受到了 TextBlob 的启发而写的, 由于现在大部分的自然语言处理库基本都是针对英文的,
# 于是写了一个方便处理中文的类库, 并且和 TextBlob 不同的是, 这里没有用 NLTK , 所有的算法都是自己实现的, 并且自带了一些训练好的字典
# 注意本程序都是处理的 unicode 编码, 所以使用时请自行 decode 成 unicode
from snownlp import SnowNLP
s = SnowNLP(u'这个东西真心很赞')  # Python2 中要用 u'' 来转成 unicode, Python3 中默认就是 Unicode
print(s.words)  # ['这个', '东西', '真心', '很', '赞']
print(s.keywords())  # ['赞', '很', '真心', '东西']
print(s.summary())  # ['这个东西真心很赞']; 对文章进行梗概, 这里只有一句话, 所以是本身
print(list(s.tags))  # [('这个', 'r'), ('东西', 'n'), ('真心', 'd'), ('很', 'd'), ('赞', 'Vg')]
print(s.sentiments)  # 0.9769663402895832 positive 的概率
print(s.pinyin)  # ['zhe', 'ge', 'dong', 'xi', 'zhen', 'xin', 'hen', 'zan']
## 找出 keywords 中的 名词
print([word for word in s.keywords() if dict(s.tags)[word] == 'n'])  # dict(s.tags) 不是函数, 不能加 ()
##################################################################
## 繁体字处理
s = SnowNLP(u'「繁體字」「繁體中文」的叫法在臺灣亦很常見。')
print(s.han)  # u'「繁体字」「繁体中文」的叫法在台湾亦很常见。'
##################################################################
## 处理一段文本 keywords(), summary() 两个重量级的函数
text = u'''
自然语言处理是计算机科学领域与人工智能领域中的一个重要方向。
它研究能实现人与计算机之间用自然语言进行有效通信的各种理论和方法。
自然语言处理是一门融语言学、计算机科学、数学于一体的科学。
因此, 这一领域的研究将涉及自然语言, 即人们日常使用的语言,
所以它与语言学的研究有着密切的联系, 但又有重要的区别。
自然语言处理并不是一般地研究自然语言,
而在于研制能有效地实现自然语言通信的计算机系统,
特别是其中的软件系统。因而它是计算机科学的一部分。
Пример #31
0
import sys
import pandas as pd  #加载pandas
from snownlp import sentiment  #加载情感分析模块
from snownlp import SnowNLP

text = pd.read_excel(u'D:/自然语言处理/川大相关微博内容.xlsx', header=0)  # 读取文本数据
text0 = text.iloc[:, 0]  # 提取所有数据
text1 = [i.decode('utf-8') for i in text0]  # 上一步提取数据不是字符而是object,所以在这一步进行转码为字符

#对语料库进行训练,把路径改成相应的位置
sentiment.train('D:/Anaconda3/Lib/site-packages/snownlp/sentiment/neg.txt',
                'D:/Anaconda3/Lib/site-packages/snownlp/sentiment/pos.txt')
#这一步是对上一步的训练结果进行保存,如果以后语料库没有改变,下次不用再进行训练
sentiment.save('D:/pyscript/sentiment.marshal')

senti = [SnowNLP(i).sentiments for i in text1]  #遍历每条评论进行预测

newsenti = []
for i in senti:
    if (i >= 0.6):
        newsenti.append(1)
    else:
        newsenti.append(-1)
text[
    'predict'] = newsenti  #将新的预测标签增加为text的某一列,所以现在text的第0列为评论文本,第1列为实际标签,第2列为预测标签
counts = 0
for j in range(len(text.iloc[:, 0])):  #遍历所有标签,将预测标签和实际标签进行比较,相同则判断正确。
    if text.iloc[j, 2] == text.iloc[j, 1]:
        counts += 1
print("准确率为:%f", (float(counts) / float(len(text))))  #输出本次预测的准确率
Пример #32
0
# ## Traditional Chinese support
# s = SnowNLP(u'「繁體字」「繁體中文」的叫法在臺灣亦很常見。')
# print(s.han)


## Topic Modeling
text = u'''
当前课程图谱中所有课程之间的相似度全部基于gensim计算,
自己写的调用代码不到一百行,topic模型采用LSI(Latent semantic indexing, 中文译为浅层语义索引),
LSI和LSA(Latent semantic analysis,中文译为浅层语义分析)这两个名词常常混在一起,
事实上,在维基百科上,有建议将这两个名词合二为一。
以下是课程图谱的一个效果图,课程为著名的机器学习专家Andrew Ng教授在Coursera的机器学习公开课,
图片显示的是主题模型计算后排名前10的相关课程,Andrew Ng教授同时也是Coursera的创始人之一
'''

# s = SnowNLP(text)
# for k in s.keywords(3):
#     print(k),
#
# for sum in s.summary(5):
#     print(sum),
#     print
#

s = SnowNLP([[u'这篇', u'文章'],
             [u'那篇', u'论文'],
             [u'这个']])
print(s.tf)
print(s.idf)

print(s.sim([u'文章']))
Пример #33
0
def convert(comment):
    snow = SnowNLP(str(comment))
    sentiments = snow.sentiments  #0(消极) ~ 1(积极)
    return sentiments
Пример #34
0
 def content_color(self, content):
     s = SnowNLP(content)
     color = s.sentiments
     keywords = s.keywords(3)
     print keywords
     return color, keywords
Пример #35
0
def divideWords(text):
    blob = SnowNLP(text)
    return blob.sentences
Пример #36
0
# -*- coding: utf8 -*-

from snownlp import SnowNLP

s = SnowNLP(u'这个东西真心很赞')

print s.words   # [u'这个', u'东西', u'真心',
                #  u'很', u'赞']

s.tags          # [(u'这个', u'r'), (u'东西', u'n'),
                #  (u'真心', u'd'), (u'很', u'd'),
                #  (u'赞', u'Vg')]

s.sentiments    # 0.9769663402895832 positive的概率

s.pinyin        # [u'zhe', u'ge', u'dong', u'xi',
                #  u'zhen', u'xin', u'hen', u'zan']

s = SnowNLP(u'「繁體字」「繁體中文」的叫法在臺灣亦很常見。')

s.han           # u'「繁体字」「繁体中文」的叫法
                # 在台湾亦很常见。'

text = u'''
自然语言处理是计算机科学领域与人工智能领域中的一个重要方向。
它研究能实现人与计算机之间用自然语言进行有效通信的各种理论和方法。
自然语言处理是一门融语言学、计算机科学、数学于一体的科学。
因此,这一领域的研究将涉及自然语言,即人们日常使用的语言,
所以它与语言学的研究有着密切的联系,但又有重要的区别。
自然语言处理并不是一般地研究自然语言,
而在于研制能有效地实现自然语言通信的计算机系统,
tr4s = TextRank4Sentence()
tr4s.analyze(text=text, lower=True, source='all_filters')

#設定只保留中文、英文、數字(去掉韓語日語德語,也會去掉表情符號等等)
#reference: https://zhuanlan.zhihu.com/p/84625185
rule = re.compile(u"[^a-zA-Z0-9\u4e00-\u9fa5]")

#print( '摘要:' )
tt = []
for i, item in enumerate(tr4s.get_key_sentences(num=3, sentence_min_len=80)):

    #print('第{}順位,利用textrank的第一次摘要: '.format(i+1))
    #print(item.index, item.weight, item.sentence)

    s = SnowNLP(item.sentence)
    #print('利用snownlp再取一次的結果: ')
    secnd_sn = s.summary(3)
    #print(secnd_sn)
    for cont in secnd_sn:
        ttt = rule.sub(' ', str(cont))
        if len(ttt.split(' ')) < 3 and len(ttt) > 12:
            tt.append(ttt)
    #print(' ')

s = SnowNLP(text)
#print('直接使用snownlp的摘要: ')
first_sn = s.summary(3)
for cont in first_sn:
    ttt = rule.sub(' ', str(cont))
    if len(ttt.split(' ')) < 3 and len(ttt) > 12:
Пример #38
0
from snownlp import SnowNLP
# from snownlp import sentiment #加载情感分析模块
import pandas as pd  # 加载pandas
import matplotlib.pyplot as plt

aa = '../data/京东评论.xls'
df = pd.read_excel(aa)  # 读取文本数据
df1 = df.iloc[:, 3]  # 提取所有数据
print(df1)

values = [SnowNLP(i).sentiments for i in df1]  # 遍历每条评论进行预测

# 输出积极的概率,大于0.5积极的,小于0.5消极的

# 保存预测值
myval = []
good = 0
bad = 0
for i in values:
    if (i >= 0.5):
        myval.append("正面")
        good = good + 1
    else:
        myval.append("负面")
        bad = bad + 1

df['预测值'] = values
df['评价类别'] = myval
df.to_excel('result2.xls')
rate = good / (good + bad)
print('好评率', '%.f%%' % (rate * 100))  # 格式化为百分比
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 12 23:23:43 2019

@author: ruanxinyu
"""

from snownlp import SnowNLP
#一、单篇微博
#(一)单篇微博的情感分析
#1.微博内容
weibo = u"""一生不长说短不短,不管人生处于哪个阶段,都应该少点执着,都需要学会时不时放空自己。
其实很多想不明白的事情,会在时间的推移下变得不是那样的重要,变得无所谓。放自己一马,让心真正休息,一步步学会放空的智慧,让生命微笑说放松。真好!"""

#2.单句情感分析
s = SnowNLP(weibo)

for sentence in s.sentences:
    print(sentence),
    score = str(SnowNLP(sentence).sentiments)
    print('Sentiment=' + score)
#通过对单句情感得分的分析,我们认为0.3以下为消极情绪,0.3-0.65为中立情绪,0.65以上为积极情绪
#    if score>str(0.65):
#        print('Sentiment:Postive')
#    elif score<str(0.3):
#        print('Sentiment:Negative')
#    else:
#        print('Sentiment:Neutral')

#3.整篇文本情感分析
Пример #40
0
def _sentiment(text):
    s = SnowNLP(text)
    return s.sentiments
Пример #41
0
from snownlp import SnowNLP

text = u"""
宁波华翔:海外资产拐点显现 并购协同助力国内增长
公司是国内优秀汽车内饰供应商,通过合资与并购实现高速增长。公司与世界知名汽车零部件公司合资,产品质量、市场地位处于国内领先水平;通过并购快速开拓新客户与新产品,营收规模高速提升;下游客户包括南北大众、宝马丰田等主流合资品牌,并通过海外并购进入德国宝马奔驰、美国通用等世界汽车商海外配套体系,成长空间拓展至全球配套市场。
  核心资产盈利能力强,随下游客户共同成长。11-12 年由于参股公司调整等非经常因素影响,净利润出现大幅下滑。但公司核心资产盈利能力优异,随整车客户完成全国布局,通过合资并购开拓新客户与新产品,非经常性因素影响消除后,业绩增速将恢复到20%左右。
  海外并购拓展公司产品种类和客户资源,为未来发展奠定基础。公司先后收购德国Sellner 和HIB 公司,借海外公司技术实力和客户资源提升内饰产品的品质,并进入德国奔驰宝马、美国通用配套体系。同时,公司参股德国Helbako 30%股权,进军汽车电子领域,并合资在国内设立生产基地,开拓国内汽车电子市场,为未来准备新的增长空间。
  欧洲车市向好,海外资产有望迎来拐点。公司通过合资收购成长,整合经验丰富,海外资产整合成功是大概率事件。海外资产在木内饰领域竞争力强,12 年收入近20 亿,亏损4000 多万,恢复正常有望贡献1-2 亿盈利,弹性巨大。近期欧洲车市现向好迹象,海外资产改善将大幅提升业绩。
"""

# s = SnowNLP(text)

# for each in s.keywords(5):
#     print each
# print "-" * 50
# for each in s.summary(5):
#     print each
# print "-" * 50
# for each in s.sentences:
#     print each
#     
# print s.tf
# print s.idf

#===============================================================================
# 相似度模块
#===============================================================================

s = SnowNLP([[u'创业', u'板', u'暴跌', u'4.37%', u'现', u'巨 阴', u'断头铡']]
             )
print s.sim([u'创业', u'板', u'暴跌', u'4.37%', u'现', u'巨 阴', u'断头铡'])
Пример #42
0
def segProcess(content):
    curr_snownlp = SnowNLP(content)
    raw_tags = list(curr_snownlp.tags)
    return filter(raw_tags)
Пример #43
0
            results = re.findall(r'[^。]*?{}[^。]*?。'.format(name), text)
            results_list = results_list + results

        # results_list=results_list+results

        results_list = list(set(results_list))  ###去重
        # print(results_list)
        if results_list == []:
            score_list.append(0.5)
            print('评分为:', 0.5)

        else:
            total_score = 0
            for content in results_list:
                print(content)
                s = SnowNLP(content)
                positive_prob = s.sentiments

                print(positive_prob)
                total_score = positive_prob + total_score

            length = len(results_list)
            average_score = total_score / length

            score_list.append(average_score)
            print(score_list)

    print(score_list)
    score_df = pd.DataFrame(score_list, columns=['情感得分'])

    save_path = 'F:\\newstart\software\category\\tool\category\deal_with_data\国泰安\snownlp\\{}'.format(
seg.save(r'E:\Python33\Lib\site-packages\snownlp\seg\seg.marshal')
>>> from snownlp import tag
>>> tag.train(r'E:\Python33\Lib\site-packages\snownlp\tag\199801.txt')
>>> tag.save(r'E:\Python33\Lib\site-packages\snownlp\tag\tag.marshal')
>>> from snownlp import sentiment
>>> sentiment.train(r'E:\Python33\Lib\site-packages\snownlp\sentiment\neg.txt', r'E:\Python33\Lib\site-packages\snownlp\sentiment\pos.txt')
#sentiment.save(r'E:\Python33\Lib\site-packages\snownlp\sentiment\sentiment.marshal')
这样训练好的文件就存储为seg.marshal了,之后修改snownlp/seg/__init__.py里的data_path指向刚训练好的文件即可

'''

from snownlp import SnowNLP

#停用词文件位置:r'E:\Python33\Lib\site-packages\snownlp\normal\stopwords.txt

s = SnowNLP('这个东西真心很赞')

#分词
print(s.words) #['这个', '东西', '真心', '很', '赞']

#词性标注
for i in s.tags:
	print(i)


('这个', 'r')
('东西', 'n')
('真心', 'd')
('很', 'd')
('赞', 'Vg')
Пример #45
0
def get_sentiment_cn(text):
    s = SnowNLP(text)
    return s.sentiments
Пример #46
0
def get_result(comment):
    s = SnowNLP(u'这个东西真心很不好')
    print(s.words)
    print(s.sentiments)
Пример #47
0
from snownlp import SnowNLP



text = '來看你喜歡的海\n.\n.\n.\n#vsco #vscodaily #vscotaiwan #iseetaiwan #igerstaiwan #igerstaipei #bravotaiwan #bpintaiwan #popdaily #bns_taiwan #instataiwan #instameettaiwan #ig_taiwan #wowtoplay #台灣 #台北 #台北景點 #日常 #thai #thailand #bangkok #bkk #pattaya #dongtan #jomtien'

text = '來看你喜歡的海台灣台北台北景點日常'



s = SnowNLP(text)
print(s.words)
s_senti = s.sentiments
print(s_senti)
#0.9893759430974675
Пример #48
0
def getKeyWords(text,keyWordsNum):
    s = SnowNLP(text)
    return s.keywords(keyWordsNum)
Пример #49
0
def extract_title(title):
    s = SnowNLP(title)
    return s.words
Пример #50
0
# -*- coding: utf-8 -*-
__author__ = 'jz'



from snownlp import SnowNLP


if __name__ == "__main__":
    a = u'this is test for something you dont know,my name is zhouwenjie,you should tell me your name right now'
    b = u'我去,这个能不能分词啊,毕业设计就靠你了'
    c = u'Natalegawa.Ảnh: dvbTỉnh Hải Nam, Trung Quốc gần đây tuyên bố sẽ cho phép cảnh sát biển kiểm tra thậm chí là chiếm giữ tàu lạ ở khu'
    s_a = SnowNLP(c)
    print(s_a.keywords(3))
    print(s_a.summary())
    print('end')
Пример #51
0
def analyze_sentiment(df_text):
    """
    natural language processing on every row from the input.
    1. for loop dataframe:
    2. preprocess text in the df.
    3. get entity using pyLTP
    4. get sentiment, keywords, summary using SnowNLP.
    5. append result to df
    Keyword Arguments:
    df_text --
    """
    df_result = pd.DataFrame(columns=[
        'datetime', 'people', 'geography', 'organization', 'keyword',
        'summary', 'score'
    ])
    for item in df_text.iterrows():
        #  print(item[1]['Conclusion'])
        logging.info(item[0])

        text = item[1]['Conclusion']
        datetime = item[1]['WritingDate']
        if not pd.isnull(text):
            text_split = preprocess_string(text)
            # 词性标注
            #            postagger = Postagger()  # 初始化实例

            words = text_split.split()  # 分词结果
            postags = postagger.postag(words)  # 词性标注

            # 命名实体识别

            #            recognizer = NamedEntityRecognizer()  # 初始化实例

            netags = recognizer.recognize(words, postags)  # 命名实体识别

            dict_netags = defaultdict(list)
            ls_netags = list(zip(netags, words))
            for x, y in ls_netags:
                dict_netags[x].append(y)

            s = SnowNLP(text)
            score = s.sentiments * 2
            # # 人名(Nh)、地名(Ns)、机构名(Ni。)
            # # B、I、E、S
            ls_organization = [
                dict_netags[x] for x in ['S-Ni', 'B-Ni', 'E-Ni', 'I-Ni']
            ]
            ls_people = [
                dict_netags[x] for x in ['S-Nh', 'B-Nh', 'E-Nh', 'I-Nh']
            ]
            ls_geography = [
                dict_netags[x] for x in ['S-Ns', 'B-Ns', 'E-Ns', 'I-Ns']
            ]
            try:
                df_result = df_result.append(
                    {
                        'datetime':
                        datetime,
                        'keyword':
                        ','.join(s.keywords()),
                        'organization':
                        list(itertools.chain.from_iterable(ls_organization)),
                        'people':
                        list(itertools.chain.from_iterable(ls_people)),
                        'geography':
                        list(itertools.chain.from_iterable(ls_geography)),
                        'summary':
                        ';'.join(s.summary()),
                        'score':
                        score
                        # 'text': text,
                    },
                    ignore_index=True)
            except:
                continue
    return df_result
#coding:utf-8
# import sys
# reload(sys)
# sys.setdefaultencoding( "utf-8" )


from snownlp import SnowNLP

str1 = u'这个东西真心很赞'
s = SnowNLP(str1)

#print str1
print str1.encode('utf-8')

sw=s.words
print sw
#print sw.encode('utf-8')         # [u'这个', u'东西', u'真心',
               		  #  u'很', u'赞']

print s.tags          # [(u'这个', u'r'), (u'东西', u'n'),
                #  (u'真心', u'd'), (u'很', u'd'),
                #  (u'赞', u'Vg')]

print s.sentiments    # 0.9830157237610916 positive的概率

print s.pinyin        # [u'zhe', u'ge', u'dong', u'xi',
                #  u'zhen', u'xin', u'hen', u'zan']


s = SnowNLP(u'「繁體字」「繁體中文」的叫法在臺灣亦很常見。')
Пример #53
0
	def emotionAnalysis(self):
		"""
		对情绪进行分析
		SnowNLP是情绪分析模块
		:return:
		"""
		x_axis = []
		y_axis = []
		for i in glob.glob("*歌曲名*"):
			count = 0
			allsen = 0
			with open(i, 'r', encoding='utf-8') as handle:
				list_of_file = handle.readlines()
				for p in list_of_file:
					# 判断文件读取航是否为空行
					p = p.strip()
					if not(len(p)):
						continue # 为空则continue,跳过不管
					# 不为空则进行情绪统计
					else:
						if "作词" in p or "作曲" in p or "混音助理" in p or "混音师" in p or "录音师" in p or "执行制作" in p or "编曲" in p:
							pass
						else:
							s = SnowNLP(p)
							s1 = SnowNLP(s.sentences[0])
							count += 1
							allsen += s1.sentiments
			i = str(i)
			# 处理文件名获得歌曲的名字
			x_axis_test = i.split("-", 1)[1].split(".", 1)[0]
			x_axis.append(x_axis_test)
			avg = int(allsen)/count
			y_axis.append(avg)

		bar = Bar("柱状图数据堆叠示例")
		bar.add("周杰伦歌曲情绪可视化", x_axis, y_axis, is_stack=True, xaxis_interval=0)
		bar.render(r"D:\PyCharm\spiderLearning\musicSpider\chart\周杰伦歌曲情绪分析.html")

		# 显示最好的五首歌
		y_axis_first = heapq.nlargest(10, y_axis)
		temp = map(y_axis.index, heapq.nlargest(10, y_axis))
		temp = list(temp)
		x_axis_first = []
		for i in temp:
			x_axis_first.append(x_axis[i])

		# 情绪积极TOP
		bar = Bar("周杰伦情绪较好的前十首歌")
		bar.add("周杰伦歌曲情绪可视化", x_axis_first, y_axis_first, is_stack=True)
		bar.render(r"D:\PyCharm\spiderLearning\musicSpider\chart\周杰伦积极歌曲TOP10.html")

		# 情绪最差TOP10
		y_axis_first = heapq.nsmallest(10, y_axis)
		temp = map(y_axis.index, heapq.nsmallest(10, y_axis))
		temp = list(temp)
		x_axis_first = []
		for i in temp:
			x_axis_first.append(x_axis[i])

		# 情绪差TOP10图
		bar = Bar("周杰伦情绪较差的前十首歌")
		bar.add("周杰伦歌曲情绪可视化", x_axis_first, y_axis_first, xaxis_interval=0,)
		bar.render(r"D:\PyCharm\spiderLearning\musicSpider\chart\周杰伦最消极歌曲TOP10.html")
Пример #54
0
def convert(comment):
    snow = SnowNLP(str(comment))
    sentiments = snow.sentiments    # 0(消极) -- 1(消极)
    return sentiments
# -*- coding: utf-8 -*-
from snownlp import SnowNLP
import codecs
import os

source = open("data.txt", "r", encoding='utf-8')
line = source.readlines()
sentimentslist = []
for i in line:
    s = SnowNLP(i)
    #print(s.sentiments)
    sentimentslist.append(s.sentiments)

import matplotlib.pyplot as plt
import numpy as np
plt.hist(sentimentslist, bins=np.arange(0, 1, 0.01), facecolor='g')
plt.xlabel('Sentiments Probability')
plt.ylabel('Quantity')
plt.title('Analysis of Sentiments')
plt.show()
                                                               id=id)
        df = pandas.read_csv(datapath, names=names, encoding='GBK')
        '''日期预处理start'''
        pandas.options.mode.chained_assignment = None
        for index, date in zip(df.index, df.date):
            if '2016' not in date and '2017' not in date:
                df.loc[index, 'date'] = '2017-' + date
        df.to_csv(datapath, mode='w', header=False, index=False)
        '''日期预处理 end'''

        sentiments = []
        for comment in df.comments:
            if comment == "转发微博":  #去除转发微博的影响
                sentiments.append(0)
            else:
                sentiments.append(SnowNLP(comment).sentiments)

        df['sentiments'] = sentiments

        #只保存时间的 年 月 日
        for index, date in zip(df.index, df.date):
            df.loc[index, 'date'] = date[0:10]

        #计算每个日期的转发数并按照日期从小到大排序
        newdf = df.date.value_counts().sort_index()

        newdate = []
        sumSentimentsOnOneday = []  #单天的情感指数
        #转换日期的格式从str为datetime.strptime,用于绘图
        SentimentsUpToNow = []
        for date in newdf.index:
import matplotlib.pyplot as plt
import pickle
from icecream import ic
from snownlp import SnowNLP
from tqdm import tqdm

with open('.\\tz.txt', 'r') as fp:
    text = ''.join(fp.readlines())

text = SnowNLP(text)
sent = text.sentences
res = []
for sen in tqdm(sent):
    s = SnowNLP(sen)
    res.append(s.sentiments)

with open('sentres.pickle', 'wb') as fp:
    pickle.dump(res, fp)

plt.hist(res, 30)
plt.show()
Пример #58
0
def get_info(base_url,start,totalnum=1):
    if not os.path.exists(path):
        os.mkdir(path)
    for questionNum in range(start,start+totalnum):
        time.sleep(0.1)
        url = base_url.format(str(questionNum))
        wb_data = requests.get(url)
        Soup = BeautifulSoup(wb_data.text,'lxml')
        print(url)
        if not Soup.select('div.question-tit'):
            print('该问题已失效')
        else:
            #反映最佳答案的标签 写一个判断
            if Soup.select('div.question-main.satisfaction-answer'):
                print('找到了最佳答案')

                print('正在处理%d问题' %questionNum)
                #获得提问标题
                ask_title = Soup.select('h3#questionTitle')[0].text
                #获得提问描述
                askContent = Soup.select('div.replenish-con')
                ask_content=''
                for item in askContent:
                    ask_content += item.text
                answerCon = Soup.select('#s_main > div.container > div.column1 > div:nth-of-type(3) > div > div.answer-con')
                if len(answerCon)>0:
                    answerContext = answerCon[0].text.strip()
                    ansText = ''
                    for i in answerContext:
                        if i!='\r' and i!= '\n' and i!='\t' and i!=' ':
                            ansText +=i
                    #用正则表达式将最佳答案中的描述分开,并找出最佳答案
                    bestAnsList = []
                    bestAnswer=''
                    if re.findall(r'追问',ansText):
                         bestAnsList = ansText.split('追问:')
                         if re.findall(r'补充',bestAnsList[0]):
                             bestAnswer = ''.join(bestAnsList[0].split('补充:'))
                else:
                    continue

                #用提问和回答进行关键词和情感分析
                #提问关键词
                ask_keyword = jieba.analyse.extract_tags(ask_title+ask_content,5)
                #回答关键词
                answer_keyword = jieba.analyse.extract_tags(bestAnswer,5)
                askKeywordList=[]
                answerKeywordList=[]
                for item in ask_keyword:
                    askKeywordList.append(item)
                for item in answer_keyword:
                    answerKeywordList.append(item)
                tmp = [val for val in askKeywordList if val in answerKeywordList]
                if len(tmp)>0:
                    keywordScore =len(tmp)*20
                else:
                    keywordScore = 0

                #情感分析
                try:
                    askSE = SnowNLP(ask_title+ask_content).sentiments
                    answerSE = SnowNLP(bestAnswer).sentiments
                    SEscore = (askSE-answerSE)**2
                    Sentiment_score = 70 - SEscore*100
                except:
                    SEscore = 0.5
                    Sentiment_score = 30


                #获得问题的点赞数和反对数
                supportNum = int(Soup.select('a.operate-support')[0].get('num'))
                opposeNum = int(Soup.select('a.operate-oppose')[0].get('num'))


                data = {
                    'ask_id':questionNum,
                    'keyword_score':len(tmp),
                    'Sentiment_score':SEscore,
                    'Support_num':supportNum,
                    'Oppose_num':opposeNum,
                    'final_score':keywordScore+Sentiment_score+opposeNum+supportNum
                }

                with open(path+'/totaldata.txt','a') as _file:
                    _text = str(str(data['Support_num'])+'\t'+str(data['Oppose_num'])+'\t'+str(data['Sentiment_score'])+'\t'+   \
                      str(data['keyword_score'])+'\t'+str(data['final_score'])+'\n')
                    _file.write(_text)

            else:
                print('问题没有最佳答案 跳过')
Пример #59
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/6 11:48
# @File    : p1_snownlp.py


from snownlp import SnowNLP

text = '其实故事本来真的只值三星当初的中篇就足够了但是啊看到最后我又一次被东野叔的反战思想打动了所以就加多一星吧'

s = SnowNLP(text)

# 1、中文分词
print(s.words)

# 2、词性标注(隐马尔可夫模型)
print(list(s.tags))

print("=" * 40)

# 3、情感分析(朴素贝叶斯分类器)
print(s.sentiments)
text2 = '这本书烂透了'
s2 = SnowNLP(text2)
print(s2.sentiments)

# 4、转化为拼音(Trie树)
print(s.pinyin)

# 5、繁体转简体
text3 = '後面這些是繁體字'
Пример #60
0
__author__ = 'Luolin'
import urllib2
from bs4 import BeautifulSoup
import urllib
from snownlp import SnowNLP

soup = BeautifulSoup(urllib2.urlopen("http://bbs.tianya.cn/post-lookout-358741-1.shtml").read())
data = soup.find('meta',{'name':'author'})
db = soup.find("div")
data = data['content'].encode('utf-8')
author =  {'d':data}
author_enc = urllib.urlencode(author)[2:]
lead_div = soup.find('div',{"class":"atl-main"})
text = lead_div.find('div',{'class':'bbs-content clearfix'}).get_text().strip().encode('utf-8')+"\r\n"
#docs = soup.findAll('div',{'js_username':author_enc})
"""
for div in docs:
    text+= div.find('div',{'class':'bbs-content'}).get_text().strip().encode('utf-8')+"\r\n"
    """

text = unicode(text.decode('utf-8'))
s = SnowNLP(text)
for key in s.keywords(10):
    if len(key)>1:
        print key