下面是从弹性搜索中获取一些数据并将该数据导出到名为“mycsvfile”的csv文件的代码。 我想更改列名,以便人类可以读取。 以下是代码:
from elasticsearch import Elasticsearch
import csv
es = Elasticsearch(["9200"])
# Replace the following Query with your own Elastic Search Query
res = es.search(index="search", body=
{
"_source": ["DTDT", "TRDT", "SPLE", "RPLE"],
"query": {
"bool": {
"should": [
{"wildcard": {"CN": "TEST1"}}
]
}
}
}, size=10)
with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x
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.writeheader()
header_present = True
w.writerow(my_dict)
当我运行上述查询时,CSV文件数据如下所示:
DTDT TRDT SPLE SACL RPLE
20170512 12/05/2017 15:39 1001 0 0
20170512 12/05/2017 15:39 1001 0 0
20170908 08/09/2017 02:42 1001 0 0
20170908 08/09/2017 06:30 1001 0 0
正如您所看到的,列名与查询中的列名相同,我希望在生成文件时为它们提供可读的名称。例如,我想让DATE和TRDT成为TIME等而不是DTDT
有人可以显示并修复我的代码,让我在CSV文件中输入列名吗?
提前谢谢
答案 0 :(得分:1)
编辑:对不起,写下我的背后的那一行。正确的,经过测试的版本如下。
with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x
header_present = False
for doc in res['hits']['hits']:
my_dict = doc['_source']
if not header_present:
fieldnames = ['name', 'name', 'name']
w = csv.DictWriter(f, fieldnames=fieldnames)
w.writeheader()
header_present = True
w.writerow(my_dict)
使脚本写出标题的原因是传递给DictWriter的my_dict.keys()。用标签列表替换这些键,编写者应该正确编写它。
答案 1 :(得分:0)
一种简单的方法是将dict用作转换表并将其写为一行而不是编写实际的DictWriter标题:
header_names = { 'DTDT': 'DATE', 'TRDT': 'TIME', ...}
with open('mycsvfile.csv', 'w') as f: # Just use 'w' mode in 3.x
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) # will write DATE, TIME, ... in correct place
header_present = True
w.writerow(my_dict)