gpt4 book ai didi

python - 在 Python 中计算字符串中的单词

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:27 26 4
gpt4 key购买 nike

我需要编写一个程序来请求字母和输入。我需要找到包含该特定字母的单词数并列出这些单词。到目前为止,我已经能够列出包含该特定字母的单词,但是我找不到包含该特定字母的单词数量。

到目前为止我的代码是:

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

关于python - 在 Python 中计算字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com