打印字符串中出现的单词次数

时间:2016-03-21 21:52:43

标签: string

我正在尝试打印字符串中出现的单词次数,这是我的代码:

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]。

1 个答案:

答案 0 :(得分: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)

这段代码基本上就是这样。