【发布时间】:2015-04-08 17:55:01
【问题描述】:
我正在尝试用以下代码替换使用 Python 的文件中出现的每个 Regex 表达式:
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)
但是,当我运行脚本时,出现以下错误:
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
我认为它读取文件不正确,但我不确定这里的实际问题是什么
【问题讨论】:
-
很抱歉,我无法真正理解您想要做什么。您的输入文件是什么样的,成功转换后应该是什么样的?
-
输入文件是一个sql语句,其中一堆变量需要从格式更改:“这是一个变量”到:this_is_a_variable,所以我试图替换空格并删除引号来自任何遵循模式的字符串:"*"
标签: python regex search replace