【问题标题】:Finding strings in Text Files in Python在 Python 的文本文件中查找字符串
【发布时间】:2018-02-12 15:00:34
【问题描述】:

我需要一个程序在文件 (P) 中查找字符串 (S),并返回它在文件中出现的次数,为此我决定创建一个函数:

def file_reading(P, S):
  file1= open(P, 'r')
  pattern = S
  match1 = "re.findall(pattern, P)"
    if match1 != None:
      print (pattern)

我知道它看起来不太好,但由于某种原因它没有输出任何东西,更不用说正确的答案了。

【问题讨论】:

  • 你为什么将re.findall() 调用用引号括起来?并且不使用您的输入文件?
  • 修正缩进。严重缩进的 Python 代码是无稽之谈。
  • 您从未真正阅读过该文件。
  • 没有。如果它是字符串,则不会调用您的函数。你记错了什么。
  • @j.evans 请不要批准大幅改变您问题中的代码执行方式的编辑。如果您希望进行此类更改,请将它们作为edit 添加到问题中,这样现有答案/cmets 的必要上下文就不会丢失。

标签: python regex


【解决方案1】:

您的代码存在多个问题。

首先,调用open() 返回一个文件对象。它不读取文件的内容。为此,您需要使用read() 或遍历文件对象。

其次,如果您的目标是计算字符串的匹配次数,则不需要正则表达式。您可以使用字符串函数count()。即便如此,将正则表达式调用放在引号中也没有意义。

match1 = "re.findall(pattern, file1.read())"

将字符串"re.findall(pattern, file1.read())"赋给变量match1

这是一个适合你的版本:

def file_reading(file_name, search_string):
    # this will put the contents of the file into a string
    file1 = open(file_name, 'r')
    file_contents = file1.read()
    file1.close()  # close the file

    # return the number of times the string was found
    return file_contents.count(search_string)

【讨论】:

  • 看在 GodOrWhoeverIsInChargeOrNot 的份上,关闭该文件
  • @brunodesthuilliers 我根据您的建议进行了更新-我同意最好是明确的,但我的理解是文件对象在超出范围时会关闭:stackoverflow.com/questions/2404430/… 编辑:我收回这一点,我刚刚阅读了第二个答案,它解释了引发异常的情况。
【解决方案2】:

您可以逐行读取而不是读取整个文件,并找到重复模式的次数并将其添加到总数中c

def file_reading(file_name, pattern):
  c = 0
  with open(file_name, 'r') as f:
    for line in f:
      c + = line.count(pattern)
  if c: print c 

【讨论】:

    【解决方案3】:

    有一些错误;让我们一一来看看:

    1. 引号中的任何内容都是字符串。将"re.findall(pattern, file1.read())" 放在引号中只会生成一个字符串。如果你真的想调用 re.findall 函数,不需要引号:)
    2. 您检查 match1 是否为 None,这确实很棒,但是您应该返回匹配项,而不是初始模式。
    3. if 语句不应缩进。

    还有:

    • 打开文件后始终关闭它!由于大多数人忘记了这样做,因此最好使用with open(filename, action) syntax

    所以,综合起来,它看起来像这样(为了清楚起见,我更改了一些变量名称):

    def file_reading(input_file, pattern):
        with open(input_file, 'r') as text_file:
            data = text_file.read()
            matches = re.findall(pattern, data)
    
            if matches:
                print(matches)  # prints a list of all strings found
    

    【讨论】:

    • 针对None 进行测试的pythonic 方法是使用身份测试,即if matches is not None:None 保证为单例)。但是由于re.findall() 如果没有匹配项则返回一个空列表,因此这里正确的测试是一个普通的if matches:
    • @brunodesthuilliers 感谢您指出这一点!这是我第一次根据反馈编辑答案。我应该编辑代码还是在最后添加注释?
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多