2014-03-06 58 views
0

我想打開並解析使用python腳本的Json文件,並在格式化後將其內容寫入另一個Json文件中,如我所願。現在我的源Json文件有字符/「 我想替換爲空白。我在解析或創建新聞文件時沒有任何問題,只是問題是該字符沒有被替換爲空白。做我做的早些時候,我已經實現了同樣的任務,但再有就是在文檔中沒有這樣的字符時Unicode編碼的一些問題

這裏是我的代碼

doubleQuote = "\"" 


try: 

    destination = open("TodaysHtScrapedItemsOutput.json","w") # open JSON file for output 
except IOError: 
    pass 

with open('TodaysHtScrapedItems.json') as f: #load json file 
    data = json.load(f) 
print "file successfully loaded" 
for dataobj in data: 
    for news in data[cnt]["body"]: 
     news = news.encode("utf-8") 
     if(news.find(doubleQuote) != -1): # if doublequotes found in first body tag 
     # print "found double quote" 
      news.replace(doubleQuote,"") 
     if(news !=""): 
      my_news = my_news +" "+ news 

    destination.write("{\"body\":"+ "\""+my_news+"\"}"+"\n") 
    my_news = "" 
    cnt= cnt + 1 

Here is how the file looks and the quotes near the red marked text should disappear

回答

0

str.replace不會改變,你需要將字符串分配回news原來string.So。

if(news.find(doubleQuote) != -1): # if doublequotes found in first body tag 
    # print "found double quote" 
     news = news.replace(doubleQuote,"") 
+0

並且解決了我的問題,但之前在其他程序中,我只是用來調用string.replace並使用它工作......現在我完全困惑......無論如何解決了我的問題...... thnx –

1

有些事情要試試。:

您應該將二進制文件寫入並讀取json文件,因此「w」變爲「wb」,您需要添加「rb」。

你可以定義你的搜索字符串爲Unicode,具有:

doubleQuote = u'"' 

您可以查找與此命令字符的整數值。

ord(u'"') 

我得到34作爲迴應。相反的功能是chr(34)。你正在尋找與json相同的雙引號的雙引號是什麼?詳情請參閱here

你不需要的,如果循環來檢查,如果消息中包含「「」。做一個替換‘新聞’就足夠了。

請嘗試以下步驟,讓我知道,如果它仍然無法正常工作。

+0

我想這... '雙引號= U '「''' 消息。替換(doubleQuote,「」)' 但仍相同,甚至將模式更改爲「wb」 –

+0

而不嘗試替換,請閱讀'「'字符並輸出整數值,如上所述。此外,請將文件讀爲二進制文件('rb') – philshem

+0

是的,它會打印34甚至將讀取模式更改爲'rb',但該文件仍然包含該字符...我認爲我的代碼找到了簡單的雙引號從文件中取代它們,但前面加'\'(如:\「)的文件不會被替換... –