最近在处理微博数据时遇到了json转化csv换行的问题,记录一下。
import pymongo
import pandas as pd
# 创建 MongoDB 客户端
client = pymongo.MongoClient("mongodb://localhost:27017/")
# 连接到数据库
db = client["mydatabase"]
# 连接到集合
collection = db["mycollection"]
# 定义查询条件
query = {"age": {"$gt": 25}} # 查询 age 大于 25 的文档
# 查询数据并导出为 CSV 文件
cursor = collection.find(query)
df = pd.DataFrame(list(cursor))
df.to_csv("output.csv", index=False)
import pymongo
import json
# 创建 MongoDB 客户端
client = pymongo.MongoClient("mongodb://localhost:27017/")
# 连接到数据库
db = client["mydatabase"]
# 连接到集合
collection = db["mycollection"]
# 定义查询条件
query = {"age": {"$gt": 25}} # 查询 age 大于 25 的文档
# 查询数据并导出为 JSON 文件
cursor = collection.find(query)
with open('output.json', 'w') as f:
for document in cursor:
f.write(json.dumps(document) + '\n')
import pandas as pd
import json
# 读取 JSON 文件
with open('data.json') as f:
json_data = json.load(f)
# 将 JSON 数据转换为 DataFrame
df = pd.json_normalize(json_data)
# 打印 DataFrame
print(df)
import pandas as pd
# 从 CSV 文件读取数据并转换为 DataFrame
df = pd.read_csv('data.csv')
# 将 DataFrame 转换为 JSON
json_data = df.to_json(orient='records')
# 打印 JSON 数据
print(json_data)
import pandas as pd
gz_data=pd.DataFrame(data)
# 保存为csv文件,指定换行符为|
# gz_data.to_csv('guangzhou.csv', sep='|', index=False, line_terminator='|\\r\\n')
# 将DataFrame转换为JSON字符串
json_str = gz_data.to_json(orient='records')
# 将JSON字符串写入到本地文件中
with open('wulumuqi.json', 'w',encoding='utf-8') as f:
f.write(json_str)
import json
import pandas as pd
with open('guangzhou.json') as f:
data = json.load(f)
df = pd.DataFrame(data)
df.head(1)