Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:从文件中读取和替换字符串(使用特殊字符)时出错_Python_Json_Python 2.7_Replace - Fatal编程技术网

Python:从文件中读取和替换字符串(使用特殊字符)时出错

Python:从文件中读取和替换字符串(使用特殊字符)时出错,python,json,python-2.7,replace,Python,Json,Python 2.7,Replace,a、 json文件: { "a": "b", "key": "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes", "c": "d" } 我尝试了以下代码: string_to_be_replace = "abcd"

a、 json文件:

{
  "a": "b",
  "key": "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes",
  "c": "d"
}
我尝试了以下代码:

string_to_be_replace = "abcd"
string_to = "graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1' nodes"
string_to_be_identified = "\"color\" = \'black\' AND \"api\" = \'demo-application-v1\'"
string_to_be_identified1 = '"color" = \'black\' AND "api" = \'demo-application-v1\''

print string_to_be_identified
print string_to_be_identified1
print string_to.replace(string_to_be_identified1,string_to_be_replace)
print string.replace(string_to, string_to_be_identified,string_to_be_replace)
输出:

这工作正常,并按预期替换字符串,但

我尝试以下方法时并非如此

方法1:

  • 以读取模式打开文件

  • 逐行获取并替换字符串

  • 输出:

    方法2:

  • 以读取模式打开文件

  • 由于文件a.json包含json数据,因此加载json文件,将json对象转换为json字符串,然后替换它

  • 代码:

    输出:

    z:{u'a':u'b',u'c':u'd',u'key':u'graph:“color”=“black”和 “api”='demo-application-v1'节点'}

    方法3:

    我假设JSON字符串中的Unicode字符可能会产生问题,所以将Unicode字符串转换为普通字符串,然后尝试替换字符串

    代码:

    输出:

    a:{'a':'b','c':'d','key':'图形:“颜色”='black'和“api”= 'demo-application-v1'节点'}

    • python版本:2.7.15
    • 使用其中一个SO答案中的byteify代码
    • JSON文件太大,无法进行手动搜索和替换
    • 在上面的示例中,python中的“和”没有区别

    虽然我当然不建议在层次结构(如JSON)中使用任何类型的上下文无关搜索和替换,但您的主要问题是您在JSON文件中搜索的字符串已转义引号(literal
    \
    字符)因此,如果您想进行纯文本搜索,您也必须考虑这些因素。您可以使用其中一个或自己添加反斜杠,例如:

    str_search = r"graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1'"
    # or, if you prefer to manually write down the string instead of declaring it 'raw':
    # str_search = "graph: \\\"color\\\" = 'black' AND \\\"api\\\" = 'demo-application-v1'"
    str_replace = "abcd"
    
    with open("/path/to/your.json", "r") as f:
        for line in f:
            print(line.replace(str_search, str_replace))
    
    对于JSON,这将产生:

    { "a": "b", "key": "abcd nodes", "c": "d" } { “a”:“b”, “键”:“abcd节点”, “c”:“d” }
    (额外的新行由
    print
    添加).

    您为什么要尝试对JSON等分层数据进行简单搜索和替换?为什么不解析JSON,正确替换所需内容,然后再次将其序列化为JSON?@zwer,JSON太大,无法访问特定的分层结构,最糟糕的是,字符串是intern显示的复杂对象中的字段在一个非统一的复杂对象数组中。现在这个字符串将来可能会作为另一个对象的一部分出现,如果它在解析逻辑中不存在,那么我们可能会错过它,所以想到了字符串替换解决方案,它将在json中不考虑景深的情况下工作。我不知道原始字符串,谢谢!@Zwer,这很有帮助:)更多我关于原始字符串的信息:更多信息:原始字符串操作不同于通常的字符串连接,颜色是用户定义的变量:例如,
    r”和color='“+color+””和\“api\”
    那么你最好做
    r”和color='“+color+r”和\“api\”
    {
      "a": "b",
      "key": "graph: \"color\" = 'black' AND \"api\" ='demo-application-v1' node",
      "c": "d"
    }
    
     with open(path + '/a.json', 'r') as file:
        loadedJson = json.load(file)
        print "z: " + str(loadedJson).replace(string_to_be_identified, string_to_be_replace)
    file.close()
    
    def byteify(input):
        if isinstance(input, dict):
            return {byteify(key): byteify(value)
                    for key, value in input.iteritems()}
        elif isinstance(input, list):
            return [byteify(element) for element in input]
        elif isinstance(input, unicode):
            return input.encode('utf-8')
        else:
            return input
    
    with open(path + '/a.json', 'r') as file:
        loadedJson = json.load(file)
        js = byteify(loadedJson)
        print "a: " + str(js).replace(string_to_be_identified, string_to_be_replace)
    
    str_search = r"graph: \"color\" = 'black' AND \"api\" = 'demo-application-v1'"
    # or, if you prefer to manually write down the string instead of declaring it 'raw':
    # str_search = "graph: \\\"color\\\" = 'black' AND \\\"api\\\" = 'demo-application-v1'"
    str_replace = "abcd"
    
    with open("/path/to/your.json", "r") as f:
        for line in f:
            print(line.replace(str_search, str_replace))
    
    { "a": "b", "key": "abcd nodes", "c": "d" }