我有一個以管道分隔的 ~4GB txt 檔案。我正在嘗試將此文本匯入 MongoDB,但您知道 MongoDB 僅支持 JSON 和 CSV 檔案。以下是到目前為止的代碼。
import pandas as pd
import csv
from pymongo import MongoClient
url = "mongodb://localhost:27017"
client = MongoClient(url)
# Creating Database Office
db = client.Office
# Creating Collection Customers
customers = db.Customers
filename = "Names.txt"
data_df = pd.read_fwf(filename, sep="|", engine="python", encoding="latin-1")
fileout = "Names.csv"
output = data_df.to_csv(fileout, sep=",")
print("Finished")
fin = open("Names.csv", "r")
file_data = fin.read()
file_csv = csv.reader(file_data)
Customers.insert_many(file_csv)
輸入檔案“Name.txt”如下所示
Reg|Name|DOB|Friend|Nationality|Profession^M
1122|Sam|01/01/2001|John|USA|Lawyer^M
2456|George|05/10/1999|Pit|Canada|Engineer^M
5645|Brad|02/06/2000|Adam|UK|Doctor^M
如果提供的文本檔案是 CSV,則只需將其匯入 MongoDB,或者如果 txt 檔案是管道分隔或任何其他分隔,則僅在將文本檔案處理為 CSV 檔案后將其匯入 MongoDB。我在 fileout 中獲得的 CSV 檔案,當手動匯入到 MongoDB 時,結果如下所示。
col1 col2
id Reg|Name|DOB|Friend|Nationality|Profession
1 1122|Sam|01/01/2001|John|USA|Lawyer
2 2456|George|05/10/1999|Pit|Canada|Engineer
3 5645|Brad|02/06/2000|Adam|UK|Doctor
我想要達到的目標如下所示。這是通過sed命令完成的。首先,我使用命令將txt檔案中的任何“,”替換為“-”
sed -i 's/,/-/g' Names.txt
然后我用“,”替換了管道分隔符:
sed -i 's/|/,/g' Names.txt
col1 col2 col3 col4 col5 col6 col7
id Reg Name DOB Friend Nationality Profession
1 1122 Sam 01/01/2001 John USA Lawyer
2 2456 George 05/10/1999 Pit Canada Engineer
3 5645 Brad 02/06/2000 Adam UK Doctor
我知道代碼沒有做任何事情。但我不知道如何使它作業。
我對所有型別的編程都是新手,我已經搜索了關于這個問題的各種答案以及網站中的各種其他相關問題,但沒有一個適合我的需要。
更新
import csv
import json
from pymongo import MongoClient
url = "mongodb://localhost:27017"
client = MongoClient(url)
db = client.Office
customer = db.Customer
jsonArray = []
with open("Names.txt", "r") as csv_file:
csv_reader = csv.DictReader(csv_file, dialect='excel', delimiter='|', quoting=csv.QUOTE_NONE)
for row in csv_reader:
jsonArray.append(row)
jsonString = json.dumps(jsonArray, indent=1, separators=(",", ":"))
jsonfile = json.loads(jsonString)
customer.insert_many(jsonfile)
這是我從評論中得到一些想法后想出的新代碼。但現在唯一的問題是我得到這個錯誤。
Traceback (most recent call last):
File "E:\Anaconda Projects\Mongo Projects\Office Tool\csvtojson.py", line 16, in <module>
jsonString = json.dumps(jsonArray, indent=1, separators=(",", ":"))
File "C:\Users\Predator\anaconda3\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\Predator\anaconda3\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
MemoryError
uj5u.com熱心網友回復:
Pandas read_fwf()用于資料位于固定列中的資料檔案。有時它們也可能有一個分隔符(通常是一個管道字符,以使資料表更易于閱讀)。
您可以使用readcsv()讀取管道分隔的檔案。只需使用sep='|':
df = pd.read_csv(filename, sep='|')
現在您可以將資料插入到 mongo 集合中,以這種方式將資料幀轉換為字典:
Customers.insert_many( df.to_dict(orient='records') )
uj5u.com熱心網友回復:
終于找到了解決辦法。
我在一個 5GB 的檔案上測驗了它,雖然速度很慢,但它仍然可以作業。它將所有資料從管道分隔的 txt 檔案匯入到 MongoDB。
import csv
import json
from pymongo import MongoClient
url_mongo = "mongodb://localhost:27017"
client = MongoClient(url_mongo)
db = client.Office
customer = db.Customer
jsonArray = []
file_txt = "Text.txt"
rowcount = 0
with open(file_txt, "r") as txt_file:
csv_reader = csv.DictReader(txt_file, dialect="excel", delimiter="|", quoting=csv.QUOTE_NONE)
for row in csv_reader:
rowcount = 1
jsonArray.append(row)
for i in range(rowcount):
jsonString = json.dumps(jsonArray[i], indent=1, separators=(",", ":"))
jsonfile = json.loads(jsonString)
customer.insert_one(jsonfile)
print("Finished")
謝謝大家的想法
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414865.html
標籤:
