使用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