我具有Python 3.x的非常基础的知识,但我需要做的是浏览文本文件,并确保未使用受限字符编写文件。
到目前为止,我有这个:
import re
#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
data = file.read().replace('\n'' ', '').replace(' ','')
#Compare text to allowed characters
if re.search('^[A-Za-z0-9' '\,\%\[\]\=_-]*$', data):
print("All good")
else:
print ("Error!")
我无法从文本文件中删除所有空格,这是我认为导致此文件出错的原因。有没有办法我可以从数据字符串中删除所有空格或让re.search接受空格。
谢谢您的帮助。
我找到了解决方案:使用\ s匹配空格字符。
import re
#Open and simplify file - turn to string
with open('test.cfg', 'r') as file:
data = file.read().replace('\n'' ', '').replace(' ','')
if not re.search('^[A-Za-z0-9' '\s\,\.\&\%\[\]\=_-]*$', data):
print ("Error!")