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

前端 未结 5 1571
悲哀的现实
悲哀的现实 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")
    
    0 讨论(0)
  • 2021-01-27 07:29

    This should work.

       from collections import Counter
       with open('myfile.txt', 'r') as f:
           words = f.read().split()
           counts = Counter(words)
    
       print counts["test"] #counts just of exact string "test"
       #find all strings containing test (e.g 'atest', 'mytest')
       print sum([val for key,val in counts.iteritems() if "test" in key])
    
    0 讨论(0)
  • You can use regular expressions:

    import re
    
    with open('myfile.txt', 'r') as f:
        txt = f.read()
    
    cnt = len(re.findall(r'\btest\b', txt))
    

    If you don't care about case sensitivity (also match Test or TEST)

    cnt = len(re.findall(r'\btest\b', txt, flags=re.I))
    
    0 讨论(0)
  • 2021-01-27 07:41

    One-liner:

    s.split().count('test')

    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题