我有一個文本文檔,我使用regex
和nltk
來查找本文檔中最常見的單詞5
。我必須打印這些單詞所屬的句子,我該怎麼做?此外,我想擴展到在多個文檔中查找常用單詞並返回它們各自的句子。使用Python打印屬於文檔中最常用單詞的句子
import nltk
import collections
from collections import Counter
import re
import string
frequency = {}
document_text = open('test.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string) #return all the words with the number of characters in the range [3-15]
fdist = nltk.FreqDist(match_pattern) # creates a frequency distribution from a list
most_common = fdist.max() # returns a single element
top_five = fdist.most_common(5)# returns a list
list_5=[word for (word, freq) in fdist.most_common(5)]
print(top_five)
print(list_5)
輸出:
[('you', 8), ('tuples', 8), ('the', 5), ('are', 5), ('pard', 5)]
['you', 'tuples', 'the', 'are', 'pard']
輸出最常出現的話,我必須打印在那裏這些話屬於,我怎麼做到這一點的句子?
如何刪除其他部分,你的代碼的輸出爲:;} {\ levelnumbers \」 01;} \ FI-360 \ li720 \ lin720} {\ LISTNAME;} \ listid1}} {\ * \ listoverridetable {\ listoverride \ listid1 \ listoverridecount0 \ LS1}} \ margl1440 \ margr1440 \ vieww14360 \ viewh11020 \ viewkind0 \ deftab720 \ f0 \ fs32 \ cf2 \ cb3 \ expnd0 \ expndtw0 \ kerning0 \ outl0 \ strokewidth0 \ strokec2在我以前的複習中,您可以從本文頂部的系列導航鏈接進入,我介紹了兩個重要的你需要掌握的python概念爲了在您的Python學習之旅中前進 \'a0 \ –
快速提示:我的文本文件開始如下:「在我以前的複習中,您可以從本文頂部的系列導航鏈接訪問,我談到了關於您需要掌握的兩個重要Python概念,以便在您的Python學習之旅中前進。「 –