我需要编写一个程序来请求字母和输入。我需要找到包含该特定字母的单词数并列出这些单词。到目前为止,我已经能够列出包含该特定字母的单词,但是我找不到包含该特定字母的单词数量。
到目前为止我的代码是:
a = input("Letter: ")
b = input("Input: ")
a=a.lower()
b=b.lower()
c=b.count(a)
print(c)
words = b.split()
print(' '.join([word for word in words if a in word]))
输出是这样的:
Letter: e
Input: ee eeeee the
8
ee eeeee the
但是,答案应该是 3 而不是 8,因为只有 3 个单词包含字母“e”。
那么,我能得到任何帮助来解决我的问题吗。
谢谢。
请您参考如下方法:
a ="ee eeeee the"
print sum("e" in x for x in a.split())
3
拆分单词并检查每个单词中是否有 e 并使用 sum 得到总数。
b.count(a) 正在计算字母的每次出现。
In [1]: a ="ee eeeee the"
In [2]: a.split()
Out[2]: ['ee', 'eeeee', 'the'] # splits into individual words
In [3]: sum("e" in x for x in a.split()) # e is in all three words so sum returns 3
Out[3]: 3
您也可以更改代码并使用 len()
final_words = [word for word in words if a in word]
c = len(final_words)
print c
final = (' '.join(final_words))
print final
