使用python计算文本文件中单词的出现次数

时间:2015-05-20 06:44:07

标签: python file python-textprocessing

我要计算文本文件中单词的出现次数。

sub = 'Date:'

#opening and reading the input file
#In path to input file use '\' as escape character
with open ("C:\\Users\\md_sarfaraz\\Desktop\\ctl_Files.txt", "r") as myfile:
    val=myfile.read().replace('\n', ' ')    


#val
#len(val)
occurence = str.count(sub, 0, len(val))

我收到此错误: -

>>> occurence = str.count('Date:', 0,len(val))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object
>>> occurence = str.count('Date:', 0,20)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a character buffer object

3 个答案:

答案 0 :(得分:2)

你过于复杂了:

open(file).read().count(WORD)

答案 1 :(得分:0)

您使用count错误。试试这个:

occurence = val.count(sub)

答案 2 :(得分:0)

如果您想知道文本文件中出现Date:字的次数,这是一种方法:

myfile = open("C:\\Users\\md_sarfaraz\\Desktop\\ctl_Files.txt", "r").read()
sub = "Date:"
occurence = myfile.count(sub)
print occurence