Đếm số lần xuất hiện một từ trong chuỗi kí tự – ITers’Desktop

Làm thế nào để đếm xem một từ “word” xuất hiện bao nhiêu lần trong một chuỗi cho trước “string”. Có một số cách có thể tham khảo như sau: Dùng hàm split để tách các từ trong chuỗi.

string = "I am dude a string dude and dude this dude dude is really starting to dude me dufe off"
num = 0
for i in string.split():
    if i == "dude":
        num += 1
print "There are %s instances of 'dude' in '%s'" % (num, string)

Trên đây là cách đơn giản nhất. Một cách khác là:

string = "word anyone here word, dude word word www internet python is awesome lorum ipsum word"
key = "word"

def count_words(string, key):
	return float(len(string) - len(string.replace(key, ''))) / float(len(key))

num = count_words(string, key)
print "string '%s' occurs %d times in string '%s'." % (key, num, string)

Hoặc dùng phương thức count của lớp string, như sau:

s = 'Nguyen Vu Ngoc Tung Tung Tung'
s.count('Tung')

Nếu cần tìm một từ xuất hiện bao nhiêu lần trong một danh sách từ thì chúng ta có thể áp dụng đối tượng của lớp Counter của module collections. Xem thêm bài Tính số lần xuất hiện một chuỗi trong một danh sách.

wordcount

Tham khảo