Python:检查文件中的特殊字符,空格,换行符

问题描述 投票:0回答:1

如果文件包含一行中的全部数据,我应该如何检查文件中的特殊字符,空格和换行符?我试过的:

#to check the any special new line as well.
import re
    file_name=input("Please enter the file name ")
    with open(file_name, 'r') as fp:
        context=fp.read()
        regex = re.compile('[@_!#$%^&*()<>?/\|} {~]') # special char check
        if(regex.search(context) == None): 
            print("No special character found")
        else: 
            print("Special character found") 
        for x in range(0,len(context)-1): # to check for spaces
            if (context[x].isspace())==True:
                print("spaces found in the file at ", x)
                break
            else:
                pass
            #print("No space found")
        for x in range(0, len(context)-1):  
            if context[x]=='\n' or context[x]=='"':   # to_check if double quote and new line
                print("Yes new line is there at", x)
                break
            else:
                pass
            #print("No new line ")
python whitespace
1个回答
0
投票

假设您的意思是文件只有1行,而不是在1行中进行检入,则此功能应有效:

def fileContainsChars(filepath, chars):
  with open(filepath, 'r') as file:
    filecontents=file.read()
  for char in chars:
    if char in filecontents:
      return True
  return False

filepath = input('Please enter the file name ')
chars = ['`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '{', '}', '[', ']', '\\', '|', ':', ';', '"', "'", '<', '>', ',', '.', '/', '?',]
if fileContainsChars(filepath, chars):
  print('file contains special chars')
if fileContainsChars(filepath, [' ']):
  print('file contains spaces')
if fileContainsChars(filepath, ['\n']):
  print('file contains new lines')

我尝试对1行和2行文件进行编码。此代码不会具有更快的regex速度,但是它更整洁,而且您不必导入额外的模块。

© www.soinside.com 2019 - 2024. All rights reserved.