使用 Python 自动化无聊的东西 - 第 8 章 - 练习 - 正则表达式搜索

Automating The Boring Stuff With Python - Chapter 8 - Exercise - Regex Search

我正在尝试完成第 8 章的练习,该练习使用用户提供的正则表达式并使用它来搜索文件夹中每个文本文件中的每个字符串。

我一直收到错误消息:

AttributeError: 'NoneType' object has no attribute 'group'

代码在这里:

import os, glob, re
os.chdir("C:\Automating The Boring Stuff With Python\Chapter 8 - \
Reading and Writing Files\Practice Projects\RegexSearchTextFiles")

userRegex = re.compile(input('Enter your Regex expression :'))

for textFile in glob.glob("*.txt"):
    currentFile = open(textFile) #open the text file and assign it to a file object
    textCurrentFile = currentFile.read() #read the contents of the text file and assign to a variable
    print(textCurrentFile)
    #print(type(textCurrentFile))
    searchedText = userRegex.search(textCurrentFile)
    searchedText.group()

当我在 IDLE 中单独尝试此操作时 shell 它起作用了:

textCurrentFile = "What is life like for those left behind when the last foreign troops flew out of Afghanistan? Four people from cities and provinces around the country told the BBC they had lost basic freedoms and were struggling to survive."
>>> userRegex = re.compile(input('Enter the your Regex expression :'))
Enter the your Regex expression :troops
>>> searchedText = userRegex.search(textCurrentFile)
>>> searchedText.group()
'troops'

但是当我 运行 它时,我似乎无法让它在代码中工作。我真的很困惑。

谢谢

由于您只是遍历所有 .txt 个文件,因此可能有些文件中没有单词 "troops"。为了证明这一点,不要调用.group(),只需执行:

print(textFile, textCurrentFile, searchedText)

如果您看到 searchedTextNone,那么这意味着 textFile(即 textCurrentFile)的内容没有 [=13] =].

您可以:

  1. 在所有 .txt 个文件中添加部队一词。
  2. 只有select目标.txt个文件,不是全部。
  3. 访问前先检查是否找到匹配项.group()
    print(searchedText.group() if searchedText else None)