截至目前,我有一个替换countChars函数的函数,
def countWords(lines):
wordDict = {}
for line in lines:
wordList = lines.split()
for word in wordList:
if word in wordDict: wordDict[word] += 1
else: wordDict[word] = 1
return wordDict
但是当我运行该程序时,它会吐出这种可憎的东西(这只是一个例子,旁边有大约两页的单词数量非常大)
before 1478
battle-field 1478
as 1478
any 1478
altogether 1478
all 1478
ago 1478
advanced. 1478
add 1478
above 1478
虽然显然这意味着代码运行得足够好,但我没有得到我想要的东西。 它需要打印文件中每个单词的次数(gb.txt,即Gettysburg地址) 显然,文件中的每个单词都不在1478次......
我对编程非常陌生,所以我有点难过......
from __future__ import division
inputFileName = 'gb.txt'
def readfile(fname):
f = open(fname, 'r')
s = f.read()
f.close()
return s.lower()
def countChars(t):
charDict = {}
for char in t:
if char in charDict: charDict[char] += 1
else: charDict[char] = 1
return charDict
def findMostCommon(charDict):
mostFreq = ''
mostFreqCount = 0
for k in charDict:
if charDict[k] > mostFreqCount:
mostFreqCount = charDict[k]
mostFreq = k
return mostFreq
def printCounts(charDict):
for k in charDict:
#First, handle some chars that don't show up very well when they print
if k == '\n': print '\\n', charDict[k] #newline
elif k == ' ': print 'space', charDict[k]
elif k == '\t': print '\\t', charDict[k] #tab
else: print k, charDict[k] #Normal character - print it with its count
def printAlphabetically(charDict):
keyList = charDict.keys()
keyList.sort()
for k in keyList:
#First, handle some chars that don't show up very well when they print
if k == '\n': print '\\n', charDict[k] #newline
elif k == ' ': print 'space', charDict[k]
elif k == '\t': print '\\t', charDict[k] #tab
else: print k, charDict[k] #Normal character - print it with its count
def printByFreq(charDict):
aList = []
for k in charDict:
aList.append([charDict[k], k])
aList.sort() #Sort into ascending order
aList.reverse() #Put in descending order
for item in aList:
#First, handle some chars that don't show up very well when they print
if item[1] == '\n': print '\\n', item[0] #newline
elif item[1] == ' ': print 'space', item[0]
elif item[1] == '\t': print '\\t', item[0] #tab
else: print item[1], item[0] #Normal character - print it with its count
def main():
text = readfile(inputFileName)
charCounts = countChars(text)
mostCommon = findMostCommon(charCounts)
#print mostCommon + ':', charCounts[mostCommon]
#printCounts(charCounts)
#printAlphabetically(charCounts)
printByFreq(charCounts)
main()
答案 0 :(得分:20)
如果你需要计算一个段落中的一些单词,那么最好使用正则表达式。
让我们从一个简单的例子开始:
import re
my_string = "Wow! Is this true? Really!?!? This is crazy!"
words = re.findall(r'\w+', my_string) #This finds words in the document
结果:
>>> words
['Wow', 'Is', 'this', 'true', 'Really', 'This', 'is', 'crazy']
请注意,“是”和“是”是两个不同的词。我的猜测是你想要将它们统计为相同,所以我们可以将所有单词大写,然后计算它们。
from collections import Counter
cap_words = [word.upper() for word in words] #capitalizes all the words
word_counts = Counter(cap_words) #counts the number each time a word appears
结果:
>>> word_counts
Counter({'THIS': 2, 'IS': 2, 'CRAZY': 1, 'WOW': 1, 'TRUE': 1, 'REALLY': 1})
你在这里好吗?
现在我们需要做的就是上面我们正在阅读文件时做的完全相同的事情。
import re
from collections import Counter
with open('your_file.txt') as f:
passage = f.read()
words = re.findall(r'\w+', passage)
cap_words = [word.upper() for word in words]
word_counts = Counter(cap_words)
答案 1 :(得分:17)
如果你使用强大的工具,这个程序实际上是一个4线程:
with open(yourfile) as f:
text = f.read()
words = re.compile(r"[\w']+", re.U).findall(text) # re.U == re.UNICODE
counts = collections.Counter(words)
正则表达式将找到所有单词,不管它们旁边的标点符号(但是将撇号作为单词的一部分计数)。
计数器的行为几乎就像字典一样,但您可以执行counts.most_common(10)
之类的操作,并添加计数等。请参阅help(Counter)
我还建议您不要创建函数printBy...
,因为只有没有副作用的函数才能轻松重用。
def countsSortedAlphabetically(counter, **kw):
return sorted(counter.items(), **kw)
#def countsSortedNumerically(counter, **kw):
# return sorted(counter.items(), key=lambda x:x[1], **kw)
#### use counter.most_common(n) instead
# `from pprint import pprint as pp` is also useful
def printByLine(tuples):
print( '\n'.join(' '.join(map(str,t)) for t in tuples) )
演示:
>>> words = Counter(['test','is','a','test'])
>>> printByLine( countsSortedAlphabetically(words, reverse=True) )
test 2
is 1
a 1
编辑以解决Mateusz Konieczny的评论:用[\ w']替换[a-zA-Z'] ...字符类\ w,根据python文档,“匹配Unicode字符;这个包括大多数可以成为任何语言单词一部分的字符,以及数字和下划线。如果使用ASCII标志,则只匹配[a-zA-Z0-9_]。“ (...但显然与撇号不匹配...)但是\ w包含_和0-9,所以如果你不想要那些并且你不使用unicode,你可以使用[a-zA -Z'];如果您正在使用unicode,则需要执行否定断言或从\ w字符类中减去[0-9_]
答案 2 :(得分:3)
你有一个简单的拼写错误 words
,你想要word
。
编辑:您似乎已编辑了源。请使用复制和粘贴,以便第一次正确使用。
编辑2:显然你并不是唯一一个容易发生拼写错误的人。真正的问题是,您需要lines
line
。我为指责你编辑来源而道歉。
答案 3 :(得分:2)
这是一个可能的解决方案,不像ninjagecko那样优雅,但仍然是:
from collections import defaultdict
dicto = defaultdict(int)
with open('yourfile.txt') as f:
for line in f:
s_line = line.rstrip().split(',') #assuming ',' is the delimiter
for ele in s_line:
dicto[ele] += 1
#dicto contians words as keys, word counts as values
for k,v in dicto.iteritems():
print k,v
答案 4 :(得分:2)
words = ['red', 'green', 'black', 'pink', 'black', 'white', 'black',
'eyes','white', 'black', 'orange', 'pink', 'pink', 'red', 'red',
'white', 'orange', 'white', "black", 'pink', 'green', 'green', 'pink',
'green', 'pink','white', 'orange', "orange", 'red']
from collections import Counter
counts = Counter(words)
top_four = counts.most_common(4)
print(top_four)
答案 5 :(得分:0)
导入馆藏并定义功能
from collections import Counter
def most_count(n):
split_it = data_set.split()
b=Counter(split_it)
return b.most_common(n)
调用指定您想要的前n个单词的函数。在我的情况下,n = 15
most_count(15)