【问题标题】:search a word in a file using python使用python搜索文件中的单词
【发布时间】:2015-09-27 07:20:26
【问题描述】:

在 shell 中,cat 文件名 | grep -i error 将从具有字符串 'error' 的文件中返回内容。

什么是 Python 等价物?

【问题讨论】:

  • 为什么不能直接打开文件逐行读取,然后打印出带有error的行?
  • Grep and Python的可能重复

标签: python search


【解决方案1】:

打开文件,遍历所有行并仅打印包含error 的行。

with open(file) as f:
    for line in f:
        if 'error' in line:
            print(line)

对于不区分大小写的匹配,

with open(file) as f:
    for line in f:
        if re.search(r'(?i)error', line):
            print(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多