我正在编写一个程序,通过使用BoyerMoore算法将模式与文本匹配的文本进行解析。我设法让代码找到所有匹配项,并打印出匹配项的位置。在
现在,我还试图获得match_表的长度和比较的次数。我对python相当陌生,程序告诉我“NameError:name‘comparison’没有定义,尽管它在def boyer_moore中使用。 程序显然没有保存变量供以后使用。很抱歉,如果这听起来很混乱,我对python还很陌生。与匹配的文本可以是found here
def make_bad_match_table(pattern):
length = len(pattern)
table = {}
for i, c in enumerate(pattern):
if i == length-1 and not c in table:
table[c] = length
else:
table[c] = length - i - 1
return table
def boyer_moore(pattern, text):
comparison = 0
match_table = []
pattern_length = len(pattern)
text_length = len(text)
if pattern_length > text_length:
return match_table
table = make_bad_match_table(pattern)
index = pattern_length - 1
pattern_index = pattern_length - 1
while index < text_length:
if pattern[pattern_index] == text[index]:
if pattern_index == 0:
match_table.append(index)
pattern_index = pattern_length - 1
index += (pattern_length * 2 - 1)
comparison +=1
else:
pattern_index -= 1
index -= 1
else:
index += table.get(text[index], pattern_length)
pattern_index = pattern_length - 1
return match_table
return comparison
if __name__ == '__main__':
file = open("CNN.txt", "r")
target = file.read()
pattern = "NASA"
print(pattern,boyer_moore(pattern, target))
print(len(match_table))
print(comparison)
也不能在return语句后面有一个语句,所以必须删除boyer_moore函数末尾的一个return。在
1.首先代替
就这么做吧
^{pr2}$2.不是这样:
就这么做吧:
希望现在能对你有所帮助。在
相关问题 更多 >
编程相关推荐