【问题标题】:Python Search & Replace With RegexPython 搜索和替换正则表达式
【发布时间】: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


【解决方案1】:

您的 cleanString 函数没有返回任何内容。因此出现“NoneType”错误。

你可能想做这样的事情:

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

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2022-06-10
    • 2013-06-14
    • 2011-04-15
    • 1970-01-01
    • 2018-05-25
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多