Compute TFIDF, keyword extraction---python

Source: Internet
Author: User
Tags idf

1. Read in the text content

Corpos = Pandas. DataFrame (columns=['FilePath','content']) forRoot, Dirs,filesinchOs.walk (R'H:\19113117-Copy'):         forNameinchFiles:filepath=root+'\\'+name F= Codecs.open (FilePath,'R','Utf-8') Content=F.read () f.close () Corpos.loc[len (Corpos)+1]=[filepath,content.strip ()]

2. The word frequency statistic will be used to divide the text manually

filepaths=[]segments=[] forFilepath,contentinchCorpos.itertuples (index=False): forIteminchContent.split ('/'): Segments.append (item) filepaths.append (FilePath) SEGMENTDF=pandas. DataFrame ({'FilePath': Filepaths,'Segments': Segments}) Segstat=Segmentdf.groupby ( by=["FilePath","Segments"]        )["Segments"].agg ({"Count": Numpy.size}). Reset_index ();

3. Calculate TF Value

textvector=segstat.pivot_table (           index='segments',           values= ' Count ' ,           columns='filePath',           fill_value=0)           TF= (1+numpy.log (textvector)). As_matrix ()

4. Calculation of IDF

def handle (x):    IDF=1+numpy.log (len (corpos)/(Numpy.sum (x>0) +1))    return  Idfzhuan=TEXTVECTOR.TIDF=zhuan.apply (handle). As_matrix () IDF=idf.reshape (8889,1)

5. Calculation TFIDF

tfidf=tf*idftfidf_df=pandas. DataFrame (TFIDF)

6, the TFIDF value of each text in the top 100 words and the corresponding TFIDF value output

file=[] forRoot, Dirs,filesinchOs.walk (R'H:\19113117-Copy'):         forNameinchFiles:name=name[0:-4] File.append (name) forIinchRange (len (corpos)): Sort=pandas. DataFrame (Tfidf_df.loc[:,i].order (Ascending=false) [: 100]). Reset_index () names=sort.columns.tolist () Names[names.index (i)]='value'Sort.columns=names Tagis=Textvector.index[sort.index]Print(File[i]) forTinchRange (len (Tagis)):Print(Tagis[t],sort.loc[t].value)

Compute TFIDF, keyword extraction---python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.