我尝试打印一个单词在字符串中出现的次数,这是我的代码:
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)
但是,当我运行程序并输入我希望它出现的单词来计算它出现的次数时,代码以它被声明的次数以及次数的格式返回它。
例如,如果我有“这是一个句子,我喜欢写一个句子]
我想选择的单词是"a",它将返回2,2,而我希望它只返回2。
发布于 2016-03-22 09:03:33
看起来你在使用Python3,看起来你的代码太复杂了。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)
这段代码基本上做到了这一点。
https://stackoverflow.com/questions/36142328
复制相似问题