一些背景故事:
我有一个程序,允许用户输入名称(例如,里斯本),并基于此 用户输入的国家/地区,该程序将遍历我的JSON文件,并打印出里斯本国家/地区(例如Jade,John)下的所有相关内容/内容。
这是我的JSON文件:
{
"user1":{
"Country":[
"China",
"USA",
"Nepal"
],
"Name":[
"Lisbon"
]
},
"user2":{
"Country":[
"Sweden",
"China",
"USA"
],
"Name":[
"Jade"
]
},
"user3":{
"Country":[
"India",
"China",
"USA"
],
"Name":[
"John"
]
}
}
我是Python的新手,我想知道如何导出我的打印结果,同时将其很好地格式化为CSV文件,这是我的打印结果:
Jade : Sweden, China, USA
John : India, China, USA
这就是我希望它在CSV文件中显示的方式:
Name Country
Jade Sweden, China, USA
John India, China, USA
这是我到目前为止所做的:
def matchCountry():
userName = raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
data = json.load(f)
def getId(name):
for userId, v in data.items():
if v['Name'][0].lower() == name:
return userId;
id = getId(userName)
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
print (v['Name'][0] + " : " + ", ".join(v['Country']))
with open('output.csv', 'ab') as csvfile:
csvwriter = csv.writer(csvfile)
for row in result.items():
csvwriter.writerow(row)
答案 0 :(得分:1)
有很多方法可以执行此操作,但是您可以考虑将数据存储在pandas dataframe中,然后将数据写入.csv。
例如,
**Compress a normal JSON object as a LZW string:**
var lzwString = JSONC.pack( json );
**Decompress using java:**
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
while (input.length() > 0) {
String s = st.longestPrefixOf(input); // Find max prefix match s.
BinaryStdOut.write(st.get(s), W); // Print s's encoding.
int t = s.length();
if (t < input.length() && code < L) // Add s to symbol table.
st.put(input.substring(0, t + 1), code++);
input = input.substring(t); // Scan past s in input.
}
BinaryStdOut.write(R, W);
BinaryStdOut.close();
这样写:
import pandas as pd
df = pd.DataFrame({'Names':['John','Jane'],
'Countries':[['Spain','India','USA'],['China','Spain','India']]})
df.to_csv('filepath_to_save',index=False)
这样做的缺点是,您在单个列中有多个值,因此不能以最吸引人的格式保存。如果您知道某人只能拥有三个或更少的国家,那么您可以做到:
Countries,Names
"[Spain,India,USA]",John
"[China,Spain,India]",Jane
其中写道:
df = pd.DataFrame({'Names':['John','Jane'],
'Country_one':['Spain','China'],
'Country_two':['India','Spain'],
'Country_three':['USA','India']})
# save to .csv ordering the columns
df.to_csv('filepath_to_save',index=False, header=True,
columns=["Names","Country_one","Country_two","Country_three"])
然后将其保存为精美的.csv格式,但缺点是存在多个
答案 1 :(得分:0)
我改为这样做,如果这是不好的编码,请更正我!
with open('output.csv', 'w') as csvfile:
csvwriter = csv.writer(csvfile, f, lineterminator='\n')
csvwriter.writerow(["Name", "Country"])
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
csvwriter.writerow([v['Name'][0], ", ".join(v['Country'])])
这是我在CSV文件中的输出:
Name Country
Jade Sweden, China, USA
John India, China, USA
答案 2 :(得分:0)
经过Python 3.6.7测试
# -*- coding: utf-8 -*-
import json
import os
def matchCountry():
userName = input("Enter user's name: ")
with open('list_of_users.json') as f:
data = json.load(f)
def getId(name):
for userId, v in data.items():
if v['Name'][0].lower() == name:
return userId;
id = getId(userName)
results = []
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
if v['Name'][0].lower() != userName.lower():
r = v['Name'][0] + "\t" + ", ".join(v['Country'])
print(r)
results.append(r)
if not os.path.exists('output.csv'):
with open('output.csv', 'w') as csvfile:
csvfile.write("Name\tCountry\n")
with open('output.csv', 'a') as csvfile:
for row in results:
csvfile.write(row + "\n")
def main():
matchCountry()
if __name__ == '__main__':
main()