注意:
斯普利特:
>>> "Hi, how are you?".split()
['Hi,', 'how', 'are', 'you?']
循環與分裂:
>>> for i in "Hi, how are you?".split():
... print i
...
Hi,
how
are
you?
它看起來像你的需要。除了字Hi,
,因爲默認情況下split()
被空白分隔,因此Hi,
保留爲您不想要的單個字符串(顯然)。計算文件中單詞的頻率。
一個好的解決方案可以是使用正則表達式,但首先保持答案簡單我回答replace()
方法。方法str.replace(old, new[, max])
返回字符串的一個副本,其中old的出現已被new替換,可選地將替換次數限制爲max。
現在檢查下面的代碼示例什麼,我想建議:
>>> "Hi, how are you?".split()
['Hi,', 'how', 'are', 'you?'] # it has , with Hi
>>> "Hi, how are you?".replace(',', ' ').split()
['Hi', 'how', 'are', 'you?'] # , replaced by space then split
循環:現在
>>> for word in "Hi, how are you?".replace(',', ' ').split():
... print word
...
Hi
how
are
you?
,怎麼算頻率:
的一種方法是使用計數器正如邁克爾建議的那樣,但是要使用你想要從空字典開始的方法。做這樣的事情代碼:
words = f.read()
wordfreq = {}
for word in .replace(', ',' ').split():
wordfreq[word] = wordfreq.setdefault(word, 0) + 1
# ^^ add 1 to 0 or old value from dict
我在做什麼?:因爲最初wordfreq
是空的,你不能在第一次分配給wordfreq[word]
(將上升鍵除外)。所以我使用了setdefault dict方法。
dict.setdefault(key, default=None)
與get()
類似,但如果密鑰尚未在dict中,將設置爲dict[key]=default
。因此,第一次當一個新的單詞出現時,我使用setdefault
在字典中使用0
來設置它,然後添加1
,並將其分配給相同的字典。
我用with open而不是單獨的open
編寫了一個等效的代碼。
with open('~/Desktop/file') as f:
words = f.read()
wordfreq = {}
for word in words.replace(',', ' ').split():
wordfreq[word] = wordfreq.setdefault(word, 0) + 1
print wordfreq
運行這樣的:
$ cat file # file is
this is the textfile, and it is used to take words and count
$ python work.py # indented manually
{'and': 2, 'count': 1, 'used': 1, 'this': 1, 'is': 2,
'it': 1, 'to': 1, 'take': 1, 'words': 1,
'the': 1, 'textfile': 1}
使用re.split(pattern, string, maxsplit=0, flags=0)
for循環只要改變:for i in re.split(r"[,\s]+", words):
,應該產生正確的輸出。
編輯:最好找到所有字母數字字符,因爲您可能有多個標點符號。
>>> re.findall(r'[\w]+', words) # manually indent output
['this', 'is', 'the', 'textfile', 'and',
'it', 'is', 'used', 'to', 'take', 'words', 'and', 'count']
使用for循環:for word in re.findall(r'[\w]+', words):
我將如何編寫代碼,而無需使用read()
:
文件是:
$ cat file
This is the text file, and it is used to take words and count. And multiple
Lines can be present in this file.
It is also possible that Same words repeated in with capital letters.
代碼是:
$ cat work.py
import re
wordfreq = {}
with open('file') as f:
for line in f:
for word in re.findall(r'[\w]+', line.lower()):
wordfreq[word] = wordfreq.setdefault(word, 0) + 1
print wordfreq
用於將lower()
轉換爲低位字母。
輸出:
$python work.py # manually strip output
{'and': 3, 'letters': 1, 'text': 1, 'is': 3,
'it': 2, 'file': 2, 'in': 2, 'also': 1, 'same': 1,
'to': 1, 'take': 1, 'capital': 1, 'be': 1, 'used': 1,
'multiple': 1, 'that': 1, 'possible': 1, 'repeated': 1,
'words': 2, 'with': 1, 'present': 1, 'count': 1, 'this': 2,
'lines': 1, 'can': 1, 'the': 1}
從這裏開始:http://docs.python.org/2/library/collections.html#counter-objects。您還需要「拆分」您的輸入,獲取單個詞,並刪除任何標點符號,請參閱:http://docs.python.org/2/library/stdtypes.html#string-methods – jonrsharpe