簡體   English   中英

Python 3 - 文本文件按單詞拆分,計算出現次數並返回已排序元組列表

[英]Python 3 - Text file splitting by word, counting occurences and returning a list of sorted tuples

我已經就此發表了一篇文章,但從那以后我設法解決了我最初遇到的問題,因為只是編輯舊問題只會讓事情變得更復雜。

我有一個包含大約 10'000 個單詞的文本文件。 function 的 output 應該是:一個元組列表,其中包含單詞和該單詞的出現次數作為降序排列的元組。 例如:out = [("word1",10),("word3",8),("word2",5)...]

所以這是我到目前為止的代碼:(請記住,這在一定程度上目前確實有效,但效率極低)

def text(inp):
    with open(inp,"r") as file:
        content = file.readlines()
        delimiters = ["\n"," ",",",".","?","!",":",";","-"]
        words = content
        spaces = ["","'",'']
        out = []
       
        for delimiter in delimiters:
            new_words = []
            
            for word in words:
                if word in spaces:
                    continue
                new_words += word.split(delimiter)
            words = new_words
  
        for word in words:
            x = (words.count(word),word)
            out.append(x)
            
    return out

我從 Stackoverflow 上的舊帖子中找到了前幾行的一些幫助。 輸入應該是文件路徑。 這在我的情況下確實有效。 第一部分(我在這里找到的行)工作得很好。 雖然列表中有空字符串等元素。 我現在的問題是:

如何對 output 進行排序,使出現次數最多的單詞排在第一位,然后按降序排列? 目前是隨機的。 另外,我不確定同一個詞是否在此列表中多次出現。 如果是,我怎樣才能讓它在 output 中只出現一次?

另外,如何使這段代碼更有效率? 我使用time.time()來檢查,它花了將近 419 秒,這顯然是非常低效的,因為任務規定它應該少於 30 秒。

對於我犯的任何錯誤以及我對此缺乏了解,我提前道歉

而不是運行這么多循環和條件。 你可以使用re.split

import re
def text(inp):
    with open(inp,"r") as file:
        content = file.readlines()
        #delimiters = ["\n"," ",",",".","?","!",":",";","-"]
        words = content
        spaces = ["","'",'']
        out = []
        temp_list=[]
        for word in words:
            #using re.split
            temp_list.extend(re.split('[\n, .?!:;-]',word))
        for word in set(temp_list):
            x = (word,temp_list.count(word))
            out.append(x)
    return out

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM