Giả sử chúng ta có một "chuỗi" và "từ" và chúng ta cần tìm số lần xuất hiện của từ này trong chuỗi của mình bằng cách sử dụng python. Đây là những gì chúng ta sẽ làm trong phần này, đếm số từ trong một chuỗi nhất định và in nó.
Đếm số từ trong một chuỗi nhất định
Phương pháp 1:Sử dụng vòng lặp for
# Phương pháp 1:Sử dụng vòng lặp for
test_stirng = input("String to search is : ") total = 1 for i in range(len(test_stirng)): if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'): total = total + 1 print("Total Number of Words in our input string is: ", total)
Kết quả
String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language Total Number of Words in our input string is: 16
#Method 2:Sử dụng vòng lặp while
test_stirng = input("String to search is : ") total = 1 i = 0 while(i < len(test_stirng)): if(test_stirng[i] == ' ' or test_stirng == '\n' or test_stirng == '\t'): total = total + 1 i +=1 print("Total Number of Words in our input string is: ", total)
Kết quả
String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language Total Number of Words in our input string is: 16
# Phương pháp 3:Sử dụng hàm
def Count_words(test_string): word_count = 1 for i in range(len(test_string)): if(test_string[i] == ' ' or test_string == '\n' or test_string == '\t'): word_count += 1 return word_count test_string = input("String to search is :") total = Count_words(test_string) print("Total Number of Words in our input string is: ", total)
Kết quả
String to search is : Python is a high level language. Python is interpreted language. Python is general-purpose programming language Total Number of Words in our input string is: 16
Trên đây là một số cách khác, để tìm số lượng từ trong chuỗi được nhập bởi người dùng.