首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现将filepath作为参数并基于python中的查询字符串显示文本列表的函数?

如何实现将filepath作为参数并基于python中的查询字符串显示文本列表的函数?
EN

Stack Overflow用户
提问于 2020-03-23 02:53:33
回答 1查看 26关注 0票数 1

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

我创建了一个函数str_search(),它接受三个参数:filepath, query, caseSensitivity

到目前为止,这是我能收集到的:

代码语言:javascript
复制
def str_search(filepath, query, caseSensitivity = False):
    list = []
    file = open(filepath, "r")
    f1 = file.readlines()

    print(f1)

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

代码语言:javascript
复制
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"]
)
EN

回答 1

Stack Overflow用户

发布于 2020-03-23 03:14:50

试试这个:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60807391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档