【问题标题】:Automating The Boring Stuff With Python - Chapter 8 - Exercise - Regex Search使用 Python 自动化无聊的东西 - 第 8 章 - 练习 - 正则表达式搜索
【发布时间】:2021-11-03 17:04:26
【问题描述】:

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

我不断收到错误:

AttributeError: 'NoneType' 对象没有属性 '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'

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

谢谢

【问题讨论】:

  • 如果search 返回None,则表示正则表达式搜索未找到匹配项。
  • @khelwood。谢谢。对我知道那个。但我认为还有更多,因为当我将文本文件中的文本字符串分配给变量 [textCurrentFile] 并创建一个名为 [userRegex] 的正则表达式对象时,输入单词“troops”。当我使用 group() 函数时,它显然能够在字符串变量中找到它

标签: python-3.x regex search


【解决方案1】:

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

print(textFile, textCurrentFile, searchedText)

如果您看到searchedTextNone,那么这意味着textFile(即textCurrentFile)的内容没有"troops" 这个词。

你可以:

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

【讨论】:

  • 谢谢。我会选择选项3;在访问 .group() 函数之前先检查是否找到匹配项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多