日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

作业 4:词频统计——基本功能

發布時間:2024/6/21 综合教程 37 生活家
生活随笔 收集整理的這篇文章主要介紹了 作业 4:词频统计——基本功能 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、基本信息

  1、本次作業的地址:https://edu.cnblogs.com/campus/ntu/Embedded_Application/homework/2088

  2、項目Git地址:https://gitee.com/ntucs/PairProg/tree/SE034_035/

二、項目分析

  (1)程序運行模塊(方法、函數)介紹

    ①任務一:給定一段英文字符串文件,統計其中各個英文單詞的出現頻率,將結果輸入result.txt文件

# filename: WordCount.py
#  注意:代碼風格

import argparse
import re
import cProfile
import pstats

from string import punctuation

def process_file(dst):  # 讀文件到緩沖區
    try:  # 打開文件
        d = open(dst, "r")
    except IOError as s:
        print(s)
        return None
    try:  # 讀文件到緩沖區
        bvffer = d.read()
    except:
        print('Read File Error!')
        return None
    d.close()
    return bvffer

def process_transform(bvffer):  # 將文本中的大寫轉換為小寫且進行非法字符的轉換
    if bvffer:
        bvffer = bvffer.lower()  # 將文本中的大寫字母轉換為小寫
        for ch in '{}!"#%()*+-,-./:;<=>?&@“”[]^_|':
            bvffer = bvffer.replace(ch, " ")  # 將文本中非法字符轉化為空格
        words = bvffer.split()  # 用空格分割字符串
        return words

def process_rowCount(bvffer):  # 計算文章的行數
    if bvffer:
        count = 1
        for word in bvffer:  # 開始計數
            if word == '
':
                count = count + 1
        print("lines:{:}".format(count))
        f = open('result.txt', 'w')
        print("lines:{:}".format(count),file=f)
        f.close()

def process_wordNumber(words):  # 通過正則表達式證明是否符合單詞標準,計算單詞個數且返回單詞字典
    if words:
        wordNew = []
        words_select = '[a-z]{4}(w)*'
        for i in range(len(words)):
            word = re.match(words_select, words[i])  # 如果不匹配,返回NULL類型
            if word:
                wordNew.append(word.group())
        print("words:{:}".format(len(wordNew)))
        f = open('result.txt', 'a')
        print("words:{:}".format(len(wordNew)),file=f)
        f.close()
        return wordNew

def process_stopwordSelect(words, stopwords):
    word_freq = {}
    # 統計每個單詞的頻率,存放在字典word_freq
    for word in words:  # 開始計數,將轉換好的words中踢除stopwords.txt中的單詞
        if word in stopwords:
            continue
        else:
            word_freq[word] = word_freq.get(word, 0) + 1  # 將符合的單詞進行計數統計
    return word_freq

def output_result(word_freq):
    if word_freq:
        sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
        for item in sorted_word_freq[:10]:  # 輸出 Top 10 頻率高的
            print("<{:}>:{:}".format(item[0], item[1]))
            f = open('result.txt','a')
            print("<{:}>:{:}".format(item[0], item[1]), file=f)
            f.close()

def main():
    #dst_Aimtxt = 'src/Gone_with_the_wind.txt'
    dstSecond = 'src/stopword.txt'
    parser = argparse.ArgumentParser()
    parser.add_argument('dst')
    args = parser.parse_args()
    dst = args.dst
    bvfferOne = process_file(dst)  # 讀目標txt文件
    bvfferSecond = process_file(dstSecond)  # 讀stopword.txt文件
    process_rowCount(bvfferOne)  # 讀目標txt文件的文章有多少行
    bvffertransformOne = process_transform(bvfferOne)  # 將目標txt文件中的文章文體及字符轉換
    bvffertransformSecond = process_transform(bvfferSecond)  # 將stopword.txt文件中的文章文體及字符轉換
    wordNew = process_wordNumber(bvffertransformOne)  # 計算目標txt文件中單詞的個數
    word_freq = process_stopwordSelect(wordNew, bvffertransformSecond)  # 輸出轉換好的words中踢除stopwords.txt中的前10個單詞
    output_result(word_freq)

if __name__ == "__main__":
    # 把分析結果保存到文件中
    cProfile.run("main()", filename="result.wordcount")
    # 創建Stats對象
    p = pstats.Stats("result.wordcount")
    # 按調用的次數進行排序,打印前10行
    p.strip_dirs().sort_stats("calls").print_stats(10)
    # 按照運行時間和函數名進行排序,打印前10行
    p.strip_dirs().sort_stats("cumulative", "name").print_stats(10)
    # 如果想知道有哪些函數調用了process_transform
    p.print_callers(0.5, "process_transform")
    # 如果想知道有哪些函數調用了process_rowCount
    p.print_callers(0.5, "process_rowCount")
    # 如果想知道有哪些函數調用了process_wordNumber
    p.print_callers(0.5, "process_wordNumber")
    # 如果想知道有哪些函數調用了process_stopwordSelect
    p.print_callers(0.5, "process_stopwordSelect")
    # 如果想知道有哪些函數調用了process_twoPhrase
    p.print_callers(0.5, "process_twoPhrase")
    # 如果想知道有哪些函數調用了process_threePhrase
    p.print_callers(0.5, "process_threePhrase")
    # 如果想知道有哪些函數調用了output_result
    p.print_callers(0.5, "output_result")
    # 查看process_buffer()函數中調用了哪些函數
    #p.print_callees("process_buffer")

    (1.1)統計文件的有效行數。

      通過文章中換行最后都會出現字符”
“來進行統計的。

def process_rowCount(bvffer):  # 計算文章的行數
    if bvffer:
        count = 1
        for word in bvffer:  # 開始計數
            if word == '
':
                count = count + 1
        print("lines:{:}".format(count))

    (1.2)統計文件的單詞總數。

      通過正則表達式來證明是否符合單詞的標準,最后輸出一個全是符合單詞標準的List表

      【正則表達式參考:https://blog.csdn.net/mark555/article/details/22379757

               和 https://baike.baidu.com/item/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/1700215】

def process_wordNumber(words):  # 通過正則表達式證明是否符合單詞標準,計算單詞個數且返回單詞字典
    if words:
        wordNew = []
        words_select = '[a-z]{4}(w)*'
        for i in range(len(words)):
            word = re.match(words_select, words[i])  # 如果不匹配,返回NULL類型
            if word:
                wordNew.append(word.group())
        print("words:{:}".format(len(wordNew)))

    (1.3)統計文件中各單詞的出現次數,最終只輸出頻率最高的10個。頻率相同的單詞,優先輸出字典序靠前的單詞。

      在統計單詞的出現頻率的時候,我們還加入了停詞表stopword.txt,計數轉換好且都符合單詞標準的List表,并且剔除stopword.txt中的單詞頻率。

def process_stopwordSelect(words, stopwords):
    word_freq = {}
    # 統計每個單詞的頻率,存放在字典word_freq
    for word in words:  # 開始計數,將轉換好的words中踢除stopwords.txt中的單詞
        if word in stopwords:
            continue
        else:
            word_freq[word] = word_freq.get(word, 0) + 1  # 將符合的單詞進行計數統計
    return word_freq

    ②任務一:通過停詞表stopword.txt去剔除一些無用的單詞(例如“there”、“was”等);統計高頻詞組。

      我們已經在任務一上已經將停詞表應用了,下面著重講訴統計高頻詞組。我們在統計高頻詞組時候是在任務一的基礎上將統計高頻詞組進行封裝,下面只展示封裝部分。

我們的想法是:將轉換為小寫、去除非法字符且都滿足單詞標準的單詞兩兩組合或者三個三個組合,最后達到統計的效果。

def process_twoPhrase(words):
    useless_twoPhrase =['they were','would have','there were','have been','that would']
    words_group = []
    for i in range(len(words) - 1):
        str = '%s %s' % (words[i], words[i + 1])
        words_group.append(str)
    word_freq = {}
    for word in words_group:
        if word in useless_twoPhrase:
            continue
        else:
            word_freq[word] = word_freq.get(word, 0) + 1  # 將詞組進行計數統計
    return word_freq

def process_threePhrase(words):
    words_group = []
    for i in range(len(words) - 2):
        str = '%s %s %s' % (words[i], words[i + 1], words[i + 2])
        words_group.append(str)
    word_freq = {}
    for word in words_group:
        word_freq[word] = word_freq.get(word, 0) + 1  # 將詞組進行計數統計
    return word_freq

  (2)程序算法的時間、空間復雜度分析。

    (2.1)程序算法的時間

      ①任務一:

      

      ②任務二:

      

    (2.2)空間復雜度分析

      就process_twoPhrase()這個函數而言,里面有兩個for循環,而且for循環內部也沒有循環。我們可以大致估計空間復雜度為O(N+n)。

  (3)程序運行案例截圖。

    ①任務一:

    

    ②任務二:

    

三、性能分析

  (1)調用的函數次數進行排序,輸出前10行

  

  (2)性能圖表

  

四、結對編程開銷時間及照片

  (1)結對編程開銷時間花費了一周時間左右。

  (2)結對編程照片

    

五、事后分析與總結

  (1)對某個問題的討論決策過程

    我們在統計高頻詞組的時候,當時討論了兩種統計高頻詞組的方法:一、單詞兩兩結合,三個三個結合;二、利用正則表達式進行統計。接著,我們還討論是不是在統計高頻詞組的時候是否也需要停詞表。

  (2)評價對方

    陳原對周怡峰的評價:周怡峰在編程方面基礎非常不錯,而且在合作的過程中積極為項目做巨大的貢獻,在查閱資料與學習方面不遺余力。非常有自己的想法,為我們的編程帶來了很多動力和樂趣,與之合作非常愉快。

周怡峰對陳原的評價:陳原編寫了大部分的代碼,在學習能力方面十分出色,從閱讀python書籍到可以編寫代碼用了4-5天的時間,積極思考問題,我不會的地方會提供幫助。在寫博客時也非常追求完美,希望下次合作。

  (3)評價整個過程:關于結對過程的建議

    對于結對編程,我們應該在結束之后積極思考它與我們單獨編程有什么區別。這次鍛煉也給我們提供了一次很好的經歷,在結對編程中我們都要積極參與,這樣我們才能積極積累很多經驗,也學到了很多,希望我們以后能有更多的機會進行結對編程。

總結

以上是生活随笔為你收集整理的作业 4:词频统计——基本功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。