2016-03-21 16 views
1

我試圖找到字符串多少特定的關鍵字,但輸出是不符合邏輯Python的 - 尋找特定關鍵字又算什麼呢

input = raw_input('Enter the statement:') //I love u 
keyword = raw_input('Enter the search keyword:') //love 

count = 0 

for i in input: 
    if keyword in i: 
     count = count + 1 

print count 
print len(input.split()) 

期望

1 
3 

現實

0 
3 
相似

請指教。謝謝

+4

提示:如果您將'print i'放入循環中,您認爲輸出是什麼?試試看看它是否符合你的預測。 – Kevin

+0

我有這樣一個,我 升 Ø v è ü –

+1

沒錯。你遍歷字符串:每個字符,而不是每個字。還記得你是如何找到*數字的?做類似的事情來迭代每個單詞。 – zondo

回答

3

input是一個字符串,所以遍歷它會給你每個字符單獨。你大概意思split它:

for i in input.split(): 

注意,使用列表理解可能比for循環更優雅:

count = len([x for x in input.split() if x in keyword]) 
+1

請注意,關鍵字i和'x ==關鍵字'方法不一樣。考慮輸入「消防員滅火」和關鍵字「火」,前者返回2計數,後者返回1. –

+0

@JaredGoguen好點,謝謝!適當編輯 – Mureinik

1

讓我們看看行for i in input。這裏,input是一個字符串,它是Python中的一個iterable。這意味着你可以這樣做:

for char in 'string': 
    print(char) 
# 's', 't', 'r', 'i', 'n', 'g' 

相反,你可以使用str.count方法。

input.count(keyword) 

正如評論指出的上方,如果你有輸入「我要一個蘋果」與關鍵字「一個」,str.count會發現兩個事件。如果您只需要一次出現,則需要拆分輸入,然後比較每個單詞是否相等。

sum(1 for word in input.split() if word == keyword) 
1

你需要把語句轉換成一個列表,像這樣:

input = raw_input('Enter the statement:').split() //I love u 
keyword = raw_input('Enter the search keyword:')  //love 

count = 0 

for i in input: 
    if keyword in i: 
     count = count + 1 

print count 
print len(input) 

這將允許循環正確識別您想要的項目。

相關問題