file_name = 'learning_python.txt'
//the text file to be opened
with open(file_name) as file_object:
//opens the text file
lines = file_object.readlines()
//reading the text as line by line
pi_string = ' '
for line in lines:
//joining the words
pi_string += line.rstrip()
word = 'python'
//this the word to be searched in text file
if word == 3 in pi_string:
//if python used 3 times in to text file
print 'The word used 3 times is:\n'
else:
print 'No words used thrice.'
//这是使用的文字'python是语言,我们喜欢python和python rocks。'在文件里面(learning_python.txt);想要计算我在代码中打开和读取的那个文本文件中使用的'python'字的次数?
答案 0 :(得分:2)
要计算字符串中字符串出现的时间,请使用count
方法。
from __future__ import print_function
file_name = 'learning_python.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ''.join(lines)
print(pi_string)
word = 'python'
if pi_string.count(word) == 3:
print('The word used 3 times is:\n {}'.format(word))
else:
print('No words used thrice.')
这会给你:
The word used 3 times is:
python
答案 1 :(得分:0)
file_name = 'learning_python.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.rstrip()
print pi_string
word = raw_input('Enter the word:>')
if word in pi_string:
print 'The word used.'
counts = pi_string.count(word)
print "The word used: "+str(counts)
else:
print 'No words such that used.'