Python 在文件中查找字符串
这里是第一个真正使用文件和I/O的计时器。我通过测试仪运行代码,测试仪通过代码调用我正在使用的不同文件。因此,我在下面将文件表示为“filename”,在该文件中查找的字符串表示为“s”。我非常确定我正在浏览代码行并正确地搜索字符串。这就是我所拥有的:Python 在文件中查找字符串,python,file,io,Python,File,Io,这里是第一个真正使用文件和I/O的计时器。我通过测试仪运行代码,测试仪通过代码调用我正在使用的不同文件。因此,我在下面将文件表示为“filename”,在该文件中查找的字符串表示为“s”。我非常确定我正在浏览代码行并正确地搜索字符串。这就是我所拥有的: def locate(filename, s): file= open(filename) line= file.readlines() for s in line: if s in line:
def locate(filename, s):
file= open(filename)
line= file.readlines()
for s in line:
if s in line:
return [line.count]
我知道回路线不对。如何将我要查找的字符串所在的行号作为列表返回 您可以使用来跟踪行号:
def locate(filename, s):
with open(filename) as f:
return [i for i, line in enumerate(f, 1) if s in line]
如果可以从第一行和第三行找到搜索的字符串,它将生成以下输出:
[1, 3]
您可以使用来跟踪行号:
def locate(filename, s):
with open(filename) as f:
return [i for i, line in enumerate(f, 1) if s in line]
如果可以从第一行和第三行找到搜索的字符串,它将生成以下输出:
[1, 3]
你可以用
示例文本文件
hello hey s hi
hola
s
def locate(filename, letter_to_find):
locations = []
with open(filename, 'r') as f:
for line_num, line in enumerate(f):
for word in line.split(' '):
if letter_to_find in word:
locations.append(line_num)
return locations
代码
hello hey s hi
hola
s
def locate(filename, letter_to_find):
locations = []
with open(filename, 'r') as f:
for line_num, line in enumerate(f):
for word in line.split(' '):
if letter_to_find in word:
locations.append(line_num)
return locations
输出
[0, 2]
我们可以看到,第0行和第2行的字符串s
。注意:计算机从0开始计数 发生了什么事
枚举它们,并在line\u num
中跟踪行号
要查找的字母在word
中,则它会将行数
附加到位置
位置
hello hey s hi
hola
s
def locate(filename, letter_to_find):
locations = []
with open(filename, 'r') as f:
for line_num, line in enumerate(f):
for word in line.split(' '):
if letter_to_find in word:
locations.append(line_num)
return locations
代码
hello hey s hi
hola
s
def locate(filename, letter_to_find):
locations = []
with open(filename, 'r') as f:
for line_num, line in enumerate(f):
for word in line.split(' '):
if letter_to_find in word:
locations.append(line_num)
return locations
输出
[0, 2]
我们可以看到,第0行和第2行的字符串s
。注意:计算机从0开始计数 发生了什么事
枚举它们,并在line\u num
中跟踪行号
要查找的字母在word
中,则它会将行数
附加到位置
位置
这些就是问题所在
for s in line:
if s in line:
您必须将行
读入除s
def locate(filename, s):
file= open(filename)
line= file.readlines()
index = 0;
for l in line:
print l;
index = index + 1
if s in l:
return index
print locate("/Temp/s.txt","s")
这些就是问题所在
for s in line:
if s in line:
您必须将行
读入除s
def locate(filename, s):
file= open(filename)
line= file.readlines()
index = 0;
for l in line:
print l;
index = index + 1
if s in l:
return index
print locate("/Temp/s.txt","s")
您的意思是返回
[i]
?我想您只需要I
?问题指出返回值应该是一个列表:“将我要查找的字符串所在的行的编号作为列表返回”。当然,如果整数是首选的,那么它应该是你建议的i
。啊!我认为这是项目和索引的结合。可能很难区分,因为没有首选输出的例子。行号和行内容显然是返回[i,行]
。结论。不清楚:PDid您的意思是返回[i]
?我想您只需要I
?问题指出返回值应该是一个列表:“将我要查找的字符串所在的行的编号作为列表返回”。当然,如果整数是首选的,那么它应该是你建议的i
。啊!我认为这是项目和索引的结合。可能很难区分,因为没有首选输出的例子。行号和行内容显然是返回[i,行]
。结论。不清楚:P