检查文本文件中的子字符串时犯的错误是什么?

问题描述 投票:0回答:1

我正在编写一个Python代码来检查文本文件中的一行是否包含特定的子字符串,如果包含,我将打印它的行号。到目前为止,它已经匹配了正确的行号和错误的行号,我不知道哪里出错了。我知道有用户函数可以做到这一点,这要容易得多,但我想知道我编写的代码有什么问题

这里,str1是给定的子字符串,myfile是文本文件。

for myline in myfile:           
        line_num = line_num + 1
        count1=0
        i=0
        for i in range (0,len(myline)-len(str1)+1):
            match1 = True
            if str1[0]==myline[i]:
                j=1
                for j in range(1,len(str1),1):
                    if str(str1[j])!=str(myline[i+j]):
                        match1 = False
                        break
                    else:
                        count1=count1+1
                        if count1 == len(str1):
                            print(line_num)
python string file-handling
1个回答
0
投票

我找到原因了 如果存在不匹配,count1 变量不会重置为 0。 而不是这个,

        for j in range(1,len(str1),1):
            if str(str1[j])!=str(myline[i+j]):
                match1 = False
                break

我应该写这个,

        for j in range(1,len(str1),1):
            if str(str1[j])!=str(myline[i+j]):
                match1 = False
                count1=0
                break
© www.soinside.com 2019 - 2024. All rights reserved.