python - 计算字符串中单词出现的次数

标签 python

我正在练习编码bat,问题是找到单词“code”在字符串中出现的次数,但“code”中的字母“d”可以替换任何字母。所以“code”的计数为1,“cope”的计数也为1。我写了一些代码,但它不起作用。我不明白为什么它不起作用。该函数为每个输入返回 0。这是我尝试过的链接 https://codingbat.com/prob/p186048

def count_code(str):
     count = 0
     str = str.lower()
     for x in str:
         if x == ‘c’ and str.find(x) + 1 == “o” and str.find(x) + 3 == “e”:
            count += 1
     return count 

最佳答案

正如蒂姆提到的,我会在此类任务中使用正则表达式,但是,如果您需要一种更简单的方法(不是最有效的方法,而是一种方法):

import string


text = 'elephant code joke cole coke man'
total = 0
for letter in string.ascii_lowercase:
    total += text.count(f'co{letter}e')
print(f'{total}')

请注意,在您的解决方案尝试中,有这样的内容:

for x in str:

除了在这种情况下应该避免名称冲突 str 之外,对于大小为 1000 个字符的文本,您将进行 1000 次迭代,减少到 26 次迭代(字母表中的字母) )使用这种方法。

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

相关文章:

python - 引发异常或引发异常()

python - 如何从路径列表中删除特定目录名

python - 使用 Surface.copy() 有时会失去透明度

python - ValueError : Input 0 of layer "max_pooling2d" is incompatible with the layer: expected ndim=4, 发现 ndim=5。收到完整形状 : (None, 3, 51, 39, 32)

python - 在单独的python线程中运行函数

python - 编码/解码有什么区别?

通过逻辑索引对 Python OpenCV 进行阈值处理

python - 在 matplotlib 中编辑堆积条形图的 x 轴刻度标签

python - 以易于编辑和阅读的方式将嵌套字典导入和导出到 Excel

python - 如何检查列表是否为空