为什么导入正则表达式会出现回溯错误?

Why import of regular expressions falling a traceback error?

正在分配 "Extracting Data With Regular Expressions"。为此,我正在导入正则表达式,但代码不起作用。我的错误是什么?

我在没有 "import" 的情况下检查了代码,它确实有效。第 2-7 行正在运行。但是它在 "import re" 第 1 行出现回溯错误。

import re    
fname = input('Enter file: ') 
if len(fname) < 1 : fname = "sample.txt"
hand = open(fname)
hd = hand.read()    
for line in hand:
line = line.rstrip()
nm = re.findall('[0-9]+',line)
print(nm)



C:\Users\Desktop\new>re.py
Enter file:
Traceback (most recent call last):
File "C:\Users\Desktop\new\re.py", line 1, in <module>
 import re
File "C:\Users\Desktop\new\re.py", line 9, in <module>
 [enter image description here][1]nm = re.findall('[0-9]+',line)
AttributeError: module 're' has no attribute 'findall'

因为您调用了文件 re.pyimport 实际上会导入此文件而不是正则表达式的内置模块。

只需将您的文件重命名为不同的名称,它就会按预期工作。