程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

当模式由一个字符组成时 - 我的方法无法正常工作,但是当我的模式由两个字符组成时 - IndexError

发布于2022-09-22 03:21     阅读(1193)     评论(0)     点赞(5)     收藏(1)


我编写了一个方法,在该方法中查找字符串中的所有模式匹配项。

def patternSearchResultShow(text, pattern, counter, positions):
    print('Text = \'' + text + '\'')
    print('Pattern = \'' + pattern + '\'')
    print('Number of pattern occurrences: ' + str(counter))
    print('The template enters into positions: ' + str(positions))
    
def patternSearch(text, pattern):
    counter = 0
    positions = []
    for i in range(len(text) - 1):
        for j in range(len(pattern)):
            if (text[i + j] != pattern[j]):
                break
        if (j == len(pattern) - 1):
            positions.append(i)
            counter = counter + 1
            
    patternSearchResultShow(text, pattern, counter, positions)

print('My pattern search:')
text = 'aaaa'
pattern = 'a'
patternSearch(text, pattern)

第一次测试:
text= 'aaaa'
pattern= 'a' 我的输出:

Number of pattern occurrences: 3
The template enters into positions: [0, 1, 2]

预期输出:

Number of pattern occurrences: 4
The template enters into positions: [0, 1, 2, 3]

好的,为了获得上述预期结果,我更改了以下代码行:
for i in range(len(text) - 1):->for i in range(len(text)):
现在我有输出:

Number of pattern occurrences: 4
The template enters into positions: [0, 1, 2, 3]

第二次测试: text= 'aaaa'
pattern= 'aa' 我的输出:

IndexError: string index out of range

解决方案


texti+j变得太大时,您正在访问外部,这会导致IndexError.

您没有找到所有匹配项的原因是因为您将范围限制为len(text)-1,因此您不测试最后一个字符。

您应该使外循环的限制取决于pattern

for i in range(len(text)-len(pattern)+1):

您还可以用切片比较替换内部循环。

if text[i:i+len(pattern)] == pattern:
    positions.append(i)
    counter += 1


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1762054/e991aa8c694d2ff69d06/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)