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

以上是其他兩種查詢使用者輸入字串中的單詞數的辦法。

更新於:30-Jul-2019

3 千次以上瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告