Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python计算文本文件中单词的出现次数_Python_File_Python Textprocessing - Fatal编程技术网

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

使用python计算文本文件中单词的出现次数,python,file,python-textprocessing,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 #le

我想数一数文本文件中出现的单词

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))
我得到了这个错误:--

发生率=str.count('Date:',0,len(val)) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 TypeError:应为字符缓冲区对象 >>>发生率=str.count('日期:',0,20) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 TypeError:应为字符缓冲区对象
你把事情复杂化了:

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

@Wajdi的答案是正确的方法。另外,请阅读“文件输入”模块。这是我想要的。谢谢“@skyline75489”。这很有帮助。谢谢你的提醒。这是非常有用的。
myfile = open("C:\\Users\\md_sarfaraz\\Desktop\\ctl_Files.txt", "r").read()
sub = "Date:"
occurence = myfile.count(sub)
print occurence