如何在python中实现一个以文件路径为参数并显示基于查询字符串的文本列表的函数



如果函数中包含查询字符串,我将尝试显示文件路径中的文本列表。

我制作了一个函数str_search(),它包含3个参数:filepath, query, caseSensitivity

到目前为止,这就是我所能召集的:

def str_search(filepath, query, caseSensitivity = False):
list = []
file = open(filepath, "r")
f1 = file.readlines()
print(f1)

以下是我想要显示的一些结果:

str_search('/filepath, 'Data')

['[Subtitle: An Essay on the Immediate Data of Consciousness]',
"On Mr. Spencer's Data of Ethics, by Malcolm Guthrie                    "
"  56721",
'The Oak Ridge ALGOL Compiler for the Control Data Corporation 1604,    '
'  50468',
'The Data of Ethics, by Herbert Spencer                                 '
'  46129',
'On-Line Data-Acquisition Systems in Nuclear Physics, 1969,             '
'  42613']
)
str_search('/filepath', 'Data', False)
['It is not a database, but it is useful for identifying eBooks so that',
'ONLINE DATABASE',
'The online database can be accessed at',
'[Subtitle: An Essay on the Immediate Data of Consciousness]',
"On Mr. Spencer's Data of Ethics, by Malcolm Guthrie                    "
"  56721"]
)

试试这个:

def str_search(filepath, query, caseSensitivity = False):
matching_lines = list ()
with open(filepath, "r") as f:
lines = file.readlines()
for line in lines:
if not caseSensitivity:
line = line.lower()
query = query.lower()
if query in line:
matching_lines.append(line)
return matching_lines

相关内容

  • 没有找到相关文章

最新更新