如何计算文本文件'learning_python.txt'中使用'python'的单词?

时间:2017-03-27 15:20:47

标签: python python-2.7

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'字的次数?

2 个答案:

答案 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.'

// https://www.facebook.com/photo.php?fbid=10155234485794201&set=a.10150187335079201.314302.560899200&type=3&theater