提问人:Priyansh Mehta 提问时间:10/28/2023 更新时间:10/28/2023 访问量:29
检查文本文件中的子字符串时出现什么错误?
What is the error I'm making when checking for substrings from a text file?
问:
我正在编写一个 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)
答:
0赞
Priyansh Mehta
10/28/2023
#1
我弄清楚了原因 如果存在不匹配,则 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
评论
str1
myline
if str1 in myline:
for line_num, myline in enumerate(myfile):