【发布时间】: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