隨機產生一個兩個漢字的合成詞

來源:互聯網
上載者:User

標籤:

# -*- coding: utf-8 -*-import randomclass GenNickName:    def __init__(self,num=30):        #print "__init__"        self.list=[]        self.wordNum=0        self.num=num        self.nickNames=[]    def getWordsFromTxt(self):        file=open("source.txt","r")        for l in file.readlines():            #print "l: " +l            line=l.decode("gbk").split()            #print len(line)            for e in line:                #print e                self.list.append(e)        #print len(self.list)        #print "l: %s" %self.list        file.close()    def genNickName(self):        self.getWordsFromTxt()        self.wordNum=len(self.list)-1        for k in range(self.num):             i=random.randint(0, self.wordNum)            j=random.randint(0, self.wordNum)            #print len(self.list)            #print "one nick name : "+self.list[i]+self.list[j]            self.nickNames.append(self.list[i]+self.list[j])    def showNames(self):        print "All nicks names:"        print "*"*50        i=0        for name in self.nickNames:            print name,            i=i+1            if(i%10==0):                print " "               print "*"*50            if __name__=="__main__":    g = GenNickName(50)    g.genNickName()    g.showNames()

代碼如上所示。

實現比較簡單,主要痛點在於,從txt檔案中讀取漢字後的字元分割。正常情況下,用.split函數即可,但是文中使用的是漢字,而漢字的編碼是gbk,所以在分割之前先要用gbk解碼。

每次運行,可以產生50個隨機組合的詞,如下所示:

All nicks names:**************************************************啊由 爐痼 柱著 摩辮 押至 炎奇 養識 勵賭 類外 通朝  馮又 郊祥 潛澤 撾打 僑篡 殺拾 傳曰 崩朕 紛慎 畔誘  墳趁 晨宋 名麟 癢盟 澳遼 粒紫 汛喃 國薩 娥畜 濟錘  稿俘 砌產 冤映 桅托 君蠟 勒玲 肯模 酮舒 蛋陪 屁謙  濕氰 梗煎 諸鄒 捍佃 音撞 革色 造菜 獵吉 字撚 報碧  **************************************************


隨機產生一個兩個漢字的合成詞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.