1. 程式人生 > >dict_文本解析(去除標點符號)

dict_文本解析(去除標點符號)

運行 結果 () AD 藝術 put hit 標點符號 nbsp

But, soft! what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,

Python的split函數可以識別空格,把詞匯看作是由空格分隔開來的詞單元,所以,“soft”和“soft!”會被視為不同的詞匯,分別為它們創建一個字典項。

由於文本中還存在大寫,“who”和“Who”也是不同的詞,分別進行統計。

通過字符串的lower、punctuation與translate

方法可以解決上述問題。其中translate是最精細的方法。以下是translate的說明文檔:

string.translate(s, table[, deletechars])

首先,從s中刪除deletechars參數(如果存在的話)指定的所有字符,然後使用table參數來翻譯字符。table是一個256個字符長的字符串,用來翻譯每個字符值,並按照序數進行索引。如果table是None值,只會執行字符刪除步驟。

這裏不指定table參數,用deletechars參數來刪除所有標點符號。Python甚至可以告訴我們,標點符號包括哪些字符:

>>> import string
>>> string.punctuation
‘!"#$%&\‘()*+,-./:;<=>?@[\\]^_`{|}~‘

我們對程序做出如下修改:

import string                                          # New Code

fname = raw_input(‘Enter the file name: ‘)
try:
    fhand = open(fname)
except:
    print ‘File cannot be opened:‘, fname
    exit()

counts = dict()
for line in fhand:
    line = line.translate(None, string.punctuation)    # New Code
    line = line.lower()                                # New Code
words = line.split() for word in words: if word not in counts: counts[word] = 1 else: counts[word] += 1 print counts

我們使用translate方法刪除了所有的標點符號,並將每一行中的字母轉換為小寫。程序主體並未發生改變。請註意,Python2.5及早期版本中,translate方法不接受None值作為第一個參數,因此使用下面的代碼來調用該方法:

print a.translate(string.maketrans(‘ ‘,‘ ‘), string.punctuation

懂得一些“Python的藝術”和“像Python一樣思考”,不難發現Python為許多常見數據分析問題內置了解決方案。隨著學習的深入,通過大量的示例代碼和技術文檔的閱讀,你會知道去哪裏尋找別人是否用Python已經解決了此類問題,從而減輕一些你的工作。

以程序運行的部分輸出結果如下:

Enter the file name: romeo-full.txt
{‘swearst‘: 1, ‘all‘: 6, ‘afeard‘: 1, ‘leave‘: 2, ‘these‘: 2,
‘kinsmen‘: 2, ‘what‘: 11, ‘thinkst‘: 1, ‘love‘: 24, ‘cloak‘: 1,
a‘: 24, ‘orchard‘: 2, ‘light‘: 5, ‘lovers‘: 2, ‘romeo‘: 40,
‘maiden‘: 1, ‘whiteupturned‘: 1, ‘juliet‘: 32, ‘gentleman‘: 1,
‘it‘: 22, ‘leans‘: 1, ‘canst‘: 1, ‘having‘: 1, ...}

查看這些輸出仍然很費事,讓Python來幫助我們找到具體要找到的信息。要做到這一點,我們需要學習Python的元組。在學習元組時會繼續使用這個例子。

dict_文本解析(去除標點符號)