发布于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
text
当i+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黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!