簡體   English   中英

Python:從文件中讀取和替換字符串(帶有特殊字符)時出錯

[英]Python: Error while reading and replacing String(with special characters) from file

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)

輸出:

 "color" = 'black' AND "api" = 'demo-application-v1' "color" = 'black' AND "api" = 'demo-application-v1' graph: abcd nodes graph: abcd nodes

這工作正常並按預期替換字符串但是

當我嘗試以下方法時不是

方法一:

  1. 以讀取模式打開文件,

  2. 逐行獲取並替換字符串

with open(path + '/a.json', 'r') as file: read_lines = file.readlines() for line in read_lines: print line.replace(string_to_be_identified,string_to_be_replace) file.close()

輸出:

 { "a": "b", "key": "graph: \\"color\\" = 'black' AND \\"api\\" ='demo-application-v1' node", "c": "d" }

方法二:

  1. 以閱讀模式打開文件,

  2. 由於文件a.json 有JSON 數據,加載JSON 文件,將JSON 對象轉換為JSON-string,然后替換它。

代碼:

 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()

輸出:

z: {u'a': u'b', u'c': u'd', u'key': u'graph: "color" = 'black' AND "api" = 'demo-application-v1 '節點'}

方法三:

我假設 JSON 字符串中的 Unicode 字符可能會產生問題,因此將 Unicode 字符串轉換為普通字符串,然后嘗試替換字符串

代碼:

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)

輸出:

a: {'a': 'b', 'c': 'd', 'key': 'graph: "color" = 'black' AND "api" = 'demo-application-v1' node'}

  • 蟒蛇版本:2.7.15
  • 使用來自 SO 答案之一的 byteify 代碼。
  • JSON 文件很大,無法進行手動搜索和替換。
  • 在上面的例子中仍然嘗試過的python中的 ' 和 " 沒有區別。

雖然我當然不建議在 JSON 等層次結構中進行任何類型的上下文無關搜索和替換,但您的主要問題是您在 JSON 文件中搜索的字符串已轉義引號(文字\\字符),因此您必須如果您想進行純文本搜索,也可以考慮這些。 您可以使用原始字符串或自己添加反斜杠,例如:

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"

}

(由print添加的額外新行)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM