0

I am trying to replace every occurrence of a Regex expression in a file using Python with this code:

import re

def cleanString(string):
    string = string.replace(" ", "_")
    string = string.replace('_"', "")
    string = string.replace('"', '')
    return string

test = open('test.t.txt', "w+")
test = re.sub(r':([\"])(?:(?=(\\?))\2.)*?\1', cleanString(r':([\"])(?:(?=(\\?))\2.)*?\1'), test)

However, when I run the script I am getting the following error:

Traceback (most recent call last):
  File "C:/Python27/test.py", line 10, in <module>
    test = re.sub(r':([\"])(?:(?=(\\?))\2.)*?\1', cleanString(r':([\"])(?:(?=(\\?))\2.)*?\1'), test)
  File "C:\Python27\lib\re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

I think it is reading the file incorrectly but I'm not sure what the actual issue is here

2
  • I am sorry, but I can't really get what you are trying to do. What does your input file look like, and what should it look like after a successful conversion? Commented Apr 9, 2015 at 20:42
  • the input file is a sql statement where a bunch of variables need to be changed from the format :"this is a variable" to :this_is_a_variable so i'm trying to replace the spaces and remove the quotes from any strings that follow the pattern :"*" Commented Apr 10, 2015 at 21:08

1 Answer 1

1

Your cleanString function is not returning anything. Ergo the "NoneType" error.

You probably want to do something like:

def cleanString(string):
    string = string.replace(" ", "_")
    string = string.replace('_"', "")
    string = string.replace('"', '')
    return string
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.