2017-10-17 60 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

我做了一些修改,可能会解决它从不工作。如果没有,如果你能提供我在最新评论中提出的要求,我可以提供更多帮助。 –