[英]How can you use Python to count the unique words (without special characters/ cases interfering) in a text document
我是 Python 新手,需要一些幫助來嘗試想出一個文本內容分析器,它可以幫助我在文本文件中找到 7 個內容:
到目前為止,我有這個 Python 程序來打印總字數:
with open('/Users/name/Desktop/20words.txt', 'r') as f:
p = f.read()
words = p.split()
wordCount = len(words)
print "The total word count is:", wordCount
到目前為止,我有這個 Python 程序來打印唯一的單詞和它們的頻率:(它不按順序,看到諸如: dog
、 dog.
、 "dog
和dog,
詞dog,
作為不同的詞)
file=open("/Users/name/Desktop/20words.txt", "r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k, v in wordcount.items():
print k, v
感謝您提供的任何幫助!
如果您知道要避免哪些字符,可以使用str.strip
從四肢刪除這些字符。
word = word.strip().strip("'").strip('"')...
這將刪除出現在單詞末端的這些字符。 這可能不如使用某些 NLP 庫那么有效,但它可以完成工作。
str.strip
文檔
當然,最困難的部分是識別句子。 您可以為此使用正則表達式,但可能仍然存在一些歧義,例如名稱和標題,其中有一個點后跟一個大寫字母。 對於單詞,您也可以使用簡單的正則表達式,而不是使用split
。 使用的確切表達取決於什么是“詞”。 最后,您可以使用collections.Counter
來計算所有這些,而不是手動執行此操作。 使用str.lower
將整個文本或單個單詞轉換為小寫。
這應該可以幫助您入門:
import re, collections
text = """Sentences start with an upper-case letter. Do they always end
with a dot? No! Also, not each dot is the end of a sentence, e.g. these two,
but this is. Still, some ambiguity remains with names, like Mr. Miller here."""
sentence = re.compile(r"[A-Z].*?[.!?](?=\s+[A-Z]|$)", re.S)
sentences = collections.Counter(sentence.findall(text))
for n, s in sentences.most_common():
print n, s
word = re.compile(r"\w+")
words = collections.Counter(word.findall(text.lower()))
for n, w in words.most_common():
print n, w
為了“更強大”,您可以使用一些自然語言工具包,但這對於此任務可能有點多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.