Python 2.7 - txt文件中的re.search无法正常工作

时间:2022-01-23 22:42:53

im having some trouble with getting re.search to work with a txt file. In my .txt file i have a small piece of code that will write a string to the file called "Python 2.7 - Written Through PyCharm" which works correctly. I then want to use a regular expression to verify that the word "Written" exists in the file.

我在使用txt文件进行re.search时遇到了一些麻烦。在我的.txt文件中,我有一小段代码,它会将一个字符串写入名为“Python 2.7 - 通过PyCharm编写”的文件,该文件正常工作。然后,我想使用正则表达式来验证文件中是否存在“Written”一词。

Here is my code:

这是我的代码:

FileOpen = open("default.txt", "r")
FileRead = FileOpen.read()
return_value = re.search(r"\bWritten\b", FileRead)
print return_value

After return_value prints then it does not find the desired word and outputs a search failure upon execution :

在return_value打印之后,它找不到所需的单词并在执行时输出搜索失败:

None

If i try the same piece of code on a simple string assigned to a variable then the match is found successfully using re.search i:e:

如果我在分配给变量的简单字符串上尝试相同的代码,则使用re.search i成功找到匹配:e:

string1 = "The fox jumped over the fence"
re.search(r"\bjumped over\b", string1)

which results in this output upon execution ::

执行时导致此输出::

sre.SRE_Match object...

But as soon as i start trying this re.search() through reading the contents in a .txt file then it seems to constantly fail with "None". If anyone can tell me where i have gone wrong as that would be greatly appreciated. Thanks.

但是一旦我开始通过读取.txt文件中的内容来尝试这个re.search(),那么它似乎总是以“无”失败。如果有人能告诉我哪里出错了,那将非常感激。谢谢。

1 个解决方案

#1


0  

You don't need regex to do this. You could do it easier.

你不需要正则表达式来做到这一点。你可以做得更轻松。

For example :

例如 :

>>> f = open("test.txt", "r")
>>> fr = f.read()
>>> if "lorem" in fr:
...    print "true"

true

Hope it helps.

希望能帮助到你。

EDIT :

Time tester :

时间测试员:

if str in str :

如果str在str中:

t = Timer("""if 'lorem' in open('test.txt', 'r').read(): print 'true'""")
print t.timeit()

19.9183969498

regex search :

正则表达式搜索:

t = Timer("""import re
print re.search(r'lorem', open('test.txt', 'r').read())
""")
print t.timeit()

31.3400061131

Note : the timeit() function repeat 1 million times.

注意:timeit()函数重复100万次。

Conclusion : "if str in str" is far faster.

结论:“如果str in str”要快得多。

#1


0  

You don't need regex to do this. You could do it easier.

你不需要正则表达式来做到这一点。你可以做得更轻松。

For example :

例如 :

>>> f = open("test.txt", "r")
>>> fr = f.read()
>>> if "lorem" in fr:
...    print "true"

true

Hope it helps.

希望能帮助到你。

EDIT :

Time tester :

时间测试员:

if str in str :

如果str在str中:

t = Timer("""if 'lorem' in open('test.txt', 'r').read(): print 'true'""")
print t.timeit()

19.9183969498

regex search :

正则表达式搜索:

t = Timer("""import re
print re.search(r'lorem', open('test.txt', 'r').read())
""")
print t.timeit()

31.3400061131

Note : the timeit() function repeat 1 million times.

注意:timeit()函数重复100万次。

Conclusion : "if str in str" is far faster.

结论:“如果str in str”要快得多。