我是 python 新手,我正在尝试执行以下作业,但我的输出与预期的不同。任何人都可以帮我解决这里的问题吗?感谢您的帮助!
作业:
在第三个程序中,我们研究一下文件内容的分类。与源代码在同一目录中有一个文件“strings.txt”,其中有几行随机字符串。这些行可以分为两组:一组仅包含字母(a-z、A-Z)和数字(0-9),一组还包含随机特殊字符(?、&、@、$ ...)。
创建一个程序,从文件中读取所有行并测试这些行。如果该行只有字母和/或数字,程序将打印“[line] was ok.”。如果该行有特殊字符,程序应该打印“[line] was invalid.”。当程序运行时,它会打印出如下内容:
5345m345ö34l was ok.
no2no123non4 was ok.
noq234n5ioqw#% was invalid.
%#""SGMSGSER was invalid.
doghdp5234 was ok.
sg,dermoepm was invalid.
43453-frgsd was invalid.
hsth())) was invalid.
bmepm35wae was ok.
vmopaem2234+0+ was invalid.
gsdm12313 was ok.
bbrbwb55be3"?"#? was invalid.
"?"#%#"!%#"&"?%%"?#?#"?" was invalid.
retrte#%#?% was invalid.
abcdefghijklmnopqrstuvxy was ok.
建议一次读取一行,使用 isalmun() 字符串测试对其进行测试,然后从那里继续。另请记住,字符串也可以以换行符 (\n) 结尾,这是允许的,但如果不将其切掉,则无法通过 .isalnum() 测试。 示例输出
5345m34534l was invalid.
no2no123non4 was ok.
noq234n5ioqw#% was invalid.
%#""SGMSGSER was invalid.
doghdp5234 was ok.
sg,dermoepm was invalid.
43453-frgsd was invalid.
hsth())) was invalid.
bmepm35wae was ok.
vmopaem2234+0+ was invalid.
gsdm12313 was ok.
gswrgsrdgrsgsig45 was ok.
)/(/)(#=%#)%/ was invalid.
++-+-+--+--+-+>-<+-<<_<-+>>++ was invalid.
我的代码是
handle = open("strings.txt","r")
content = handle.read()
content.isalnum()
for i in content:
if content.isalnum()==True:
print(content,"was ok")
else:
print(content,"was invalid")
handle.close()
我的输出是
5345m34534l
no2no123non4
noq234n5ioqw#%
%#""SGMSGSER
doghdp5234
sg,dermoepm
43453-frgsd
hsth()))
bmepm35wae
vmopaem2234+0+
gsdm12313
gswrgsrdgrsgsig45
)/(/)(#=%#)%/
++-+-+--+--+-+>-<+-<<_<-+>>++. was invalid
5345m34534l
no2no123non4
noq234n5ioqw#%
%#""SGMSGSER
doghdp5234
sg,dermoepm
43453-frgsd
hsth()))
bmepm35wae
vmopaem2234+0+
gsdm12313
gswrgsrdgrsgsig45
)/(/)(#=%#)%/
++-+-+--+--+-+>-<+-<<_<-+>>++. was invalid
5345m34534l
no2no123non4
noq234n5ioqw#%
%#""SGMSGSER
doghdp5234
sg,dermoepm
43453-frgsd
hsth()))
bmepm35wae
vmopaem2234+0+
gsdm12313
gswrgsrdgrsgsig45
)/(/)(#=%#)%/
++-+-+--+--+-+>-<+-<<_<-+>>++. was invalid
# etc ad nauseum...
我做错了什么?
最佳答案
handle = open("strings.txt","r")
content = handle.read() # <= here you read in the entire file
content.isalnum()
for i in content: # <= here you iterate over each **character** of the file
if content.isalnum()==True:
print(content,"was ok")
# ^ here you print the entire input file each time
else:
print(content,"was invalid")
# ^ (ditto) which is why you have so much output
handle.close()
相反,尝试
with open("strings.txt") as inf:
for line in inf:
line = line.rstrip()
if line.isalnum():
print("{} was ok".format(line))
else:
print("{} was invalid".format(line))
关于python 过滤文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22213598/