我有一个文本文件file1.txt。我已经对其进行了预处理(清洁)。像replace(“-”,“”)等操作。现在,我想对纯文本字符串执行更多操作。如何检查字符串是否已清理,即没有@!#$%^等任何特殊字符?如果不清理,应该打印无效的条目?我可以不使用re来做到吗?
def process():
with open("file1.txt",'r') as a:
text = a.read #toconvert into string
for ch in ['_','-']:
text = text.replace(ch,"")
return text
process()
答案 0 :(得分:2)
无需使用正则表达式,您可以执行以下操作:
special_char = '@!#$%^' # maybe string.punctuation?
text ='I love pizza and chips@'
print("Invalid") if any(c in special_char for c in text) else print("Valid")
要回答第二个问题,请写出以下情况:
ch = '@#$%^&*'
with open(cleanfile, 'r') as s:
s = s.readlines()
if any(c in ch for c in s):
print('Invalid')
else:
li = s.split()