2016-03-21 77 views
0

我想打印一個字一個字符串中出現的次數發生了一句話,這是我的代碼:打印多少次在一個字符串

count = 0 
wordfreq = 0 

sentence = input("Enter a sentence: ") 
word = input("Enter a word within the setence: ") 

sentence2 = sentence.split() 

wordcount = [sentence2.count.(word) for word in sentence2] 

print (wordcount) 

然而,當我運行該程序,並輸入我希望它計算它發生的次數,代碼以它所表達的次數和次數的格式返回它。

舉例來說,如果我有「這是一個句子,我喜歡寫一個句子]

,我想選字是‘一’,它將返回[2,2],而我希望它只是返回[2]。

+2

如果使用使用的語言標記問題,它會有所幫助。 – Pullie

回答

0

它看起來像你使用Python 3 它看起來像你的代碼是過於複雜。wordcount = [sentence2.count.(word) for word in sentence2]僅需要wordcount = sentence2.count.(word)

如果你想找到一個字符串中的一組字符...

count = 0 

sentence = input("Enter a sentence: ") 
word = input("Enter a word within the setence: ") 

sentence2 = list(sentence) 
word2 = list(word) 

for i in range(0, len(sentence2)-len(word2)+1): 
    trying = sentence2[i:len(word2)+i] 
    if trying == word2: 
     count+=1 

print (count) 

這段代碼基本上是這樣做的。