2017-10-17 78 views
0

下面的查詢是抓取數據並創建CSV文件,我遇到的問題是名爲'SPLE'的源將數據存儲在數據庫中,數字爲0,1,50 。將數值數據更改爲CSV文件中的文本

然而在CSV這些數字被收集在CSV和創建CSV那些數來表示的話,例如當我想以某種方式,

0 =真

1 =假

50 =待定

有人可以告訴我這是怎麼做的,請問,我一直在努力呢?

我的代碼:

from elasticsearch import Elasticsearch 
import csv 

es = Elasticsearch(["9200"]) 

res = es.search(index="search", body= 
       { 
        "_source": ["DTDT", "TRDT", "SPLE", "RPLE"], 
        "query": { 
         "bool": { 
          "should": [ 
           {"wildcard": {"CN": "TEST*"}} 

          ] 
         } 
        } 
}, size=10) 



header_names = { 'DTDT': 'DATE', 'SPLE': 'TAG', ...} 

with open('mycsvfile.csv', 'w') as f: 
    header_present = False 
    for doc in res['hits']['hits']: 
     my_dict = doc['_source'] 
     if not header_present: 
      w = csv.DictWriter(f, my_dict.keys()) 
      w.writerow(header_names) 
      header_present = True 


     w.writerow(my_dict) 

CSV文件的輸出是:

Date  SPLE  Venue 
20171016 1  Central 
20171016 1  Central 
20171016 0  Central 
20171016 0  Central 
20171016 50  Central 
20171016 0  Central 
20171016 1  Central 

FYI:

我曾嘗試使用熊貓但是我無法安裝熊貓,所以我我想知道是否有其他解決方法?

+0

在for循環中的w.writerow(my_dict)之前,根據需要更改'my_dict'的內容。 – ZdaR

+0

你能告訴我嗎?我想我做錯了 – Rich

回答

1

您可以更改值爲您可以將它寫入csv:

mapping = {0: "True", 
      1: "False", 
      50: "Pending"} 
# Map `SPLE` 
sple = my_dict['SPLE'] 
my_dict['SPLE'] = mapping.get(int(sple), sple) 

# Map `NME` 
nme = my_dict['NME'] 
my_dict['NME'] = mapping.get(int(nme), nme) 


w.writerow(my_dict) 
+0

不幸的是,這是行不通的。我在我的w.writerow(my_dict) – Rich

+0

之前添加了你的代碼,我做了一個小小的修改(將脾臟轉換爲int)。 –

+0

它會拋出一個錯誤嗎? –

0

沒有看到my_dict的內容,這只是一個最好的猜測,但我會盡力協助陳述我的假設。

對於my_dict是這樣的:

my_dict = {"DATE": ..., "SPLE": ..., ...} 

w.writerow(my_dict)之前,你可以解析SPLE進入你想要什麼:

my_dict["SPLE"] = str(bool(int(my_dict["SPLE"]))) if int(my_dict["SPLE"]) in [0,1] else "Pending" 

的是一種緊湊的形式:

# Check to see if current "SPLE" value can be described 
# as True (1) or False (0) 
if int(my_dict["SPLE"]) in [0,1]: 
    # Yes it can, so change it to True or False string by type conversion 
    my_dict["SPLE"] = str(bool(int(my_dict["SPLE"]))) 
else: 
    # Entry is not a 0 or 1 so not described by true or false 
    # assign to "Pending" 
    my_dict["SPLE"] = "Pending" 
+0

你能告訴我我在哪裏添加這個代碼。我在w.writerow之前添加了它,但失敗了。 – Rich

+0

在'w.writerow()'之前寫的應該這樣做。你可以發佈你的錯誤,併爲我打印一行'my_dict'(在'my_dict = doc ['_ source']')之後直接放置'print(my_dict)')? –

+0

我做了一些修改,可能會解決它從不工作。如果沒有,如果你能提供我在最新評論中提出的要求,我可以提供更多幫助。 –