简体   繁体   中英

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

I have a file consists of many strings. Looks like

sdfsdf sdfsdfsdf sdfsdfsdf test gggg uff test test fffffffff sdgsdgsdgsdg sdgsdgsdgsdg uuuttt 555555555 ddfdfdfff dddd4444 66677565 sdfsdf5 556e4ergferg ergdgdfgtest kdfgdfgfg test

How to count all words "test". I tried, but I have only this result

f = open("file")
words =  0
for s in f:
    i = s.find('test')
    if i > -1:
        words += 1
print(words)
f.close()

And this script counts only strings where contain word "test". How to count words?

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")

单线:

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

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])

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))

It will count number of test s 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM