Python 程式來統計給定字串中的單詞數?
假設我們有一個“字串”和一個“單詞”,我們需要使用 python 在字串中查詢該單詞出現的次數。這就是我們本節將要做的工作,統計給定字串中的單詞數並打印出來。
統計給定字串中的單詞數
方法 1:使用 for 迴圈
#方法 1:使用 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)結果
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
#方法 2:使用 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)結果
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
#方法 3:使用函式
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)結果
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
以上是其他兩種查詢使用者輸入字串中的單詞數的辦法。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP