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

counting occurence of a word in a text file using python

我正在尝试计算文本文件中某个单词的出现次数。

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

你太复杂了:

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

您使用的 count 有误。试试这个:

occurence = val.count(sub)

如果您想知道单词 Date: 在文本文件中出现了多少次,这是一种方法:

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