在Python中查找文本文件中的字符串

2024-06-16 11:52:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 文件函数字符串程序reifdefopen
3条回答

您的代码有多个问题。你知道吗

首先,调用^{}返回一个file对象。它不读取文件的内容。为此,您需要使用read()或遍历file对象。你知道吗

其次,如果您的目标是计算字符串的匹配数,则不需要正则表达式。您可以使用字符串函数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)

有几个错误,让我们逐一检查:

  1. 引号中的任何东西都是字符串。把"re.findall(pattern, file1.read())"放在引号里就是一个字符串。如果你真的想打电话给关于芬德尔函数,不需要引号:)
  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

您可以逐行读取,而不是读取整个文件,然后找到模式重复的次数,并将其添加到总计数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 

相关问题 更多 >