How to count word “test” in file on Python?

前端 未结 5 1569
悲哀的现实
悲哀的现实 2021-01-27 07:19

I have a file consists of many strings. Looks like

sdfsdf sdfsdfsdf sdfsdfsdf test gggg uff test test fffffffff sdgsdgsdgsdg sdgsdgsdgsdg uuuttt 5

5条回答
  •  再見小時候
    2021-01-27 07:50

    It will count number of tests in the whole file:

    f = open('my_file.txt', 'r')
    num_tests = len([word for word in f.read().split() if word == 'test'])
    f.close()
    

    Note that it will NOT match words like tester, tested, testing, etc.... If you want to also match them, use instead:

    f = open('my_file.txt', 'r')
    num_tests = len([word for word in f.read().split() if 'test' in word])
    f.close()
    

提交回复
热议问题