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

前端 未结 5 1690
悲哀的现实
悲哀的现实 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:27

    If you want to find all matches:

    with open("file") as f:
        numtest = f.read().count("test")
    

    If you want to find only word matches:

    with open("file") as f:
        numtest = f.read().split().count("test")
    

提交回复
热议问题