免责声明:关于mongo,我是新手。。
因此,我从文本文件中获取了此数据,然后将其处理为“ python字典”格式,以便可以将其插入使用Pymongo创建的集合中。
原始数据已更改为文本,道歉...,可在此处在pastebin上查看Link to raw data text
这是python中用于插入的格式化字典
[{'Poll_Name': 'ECU', 'Date': '2020-05-07', 'Sample_Size': '--', 'MoE': '--', 'Biden (D)': '46', 'Trump(R)': '43', 'Spread': 'Trump +3'}, {'Poll_Name': 'WRAL-TV', 'Date': '2020-04-23', 'Sample_Size': '580 LV', 'MoE': '5.5', 'Biden (D)': '45', 'Trump(R)': '50', 'Spread': 'Biden +5'}, {'Poll_Name': 'PPP (D)', 'Date': '2020-04-14', 'Sample_Size': '1318 RV', 'MoE': '2.7', 'Biden (D)': '47', 'Trump(R)': '48', 'Spread': 'Biden +1'}, {'Poll_Name': 'Civitas', 'Date': '2020-04-05', 'Sample_Size': '500 LV', 'MoE': '4.4', 'Biden (D)': '49', 'Trump(R)': '42', 'Spread': 'Trump +7'}]
我将所有字典数据都插入到数组中,并且我打算用它来执行insertmany()。
这里是我到目前为止以字典格式导出此数据的代码
def export_Data(filename): export_List = [] #list that will contain the dictionary values of the data key_List = ["Poll_Name", "Date", "Sample_Size", "MoE", "Biden (D)", "Trump(R)", "Spread"] #list of keys for each value count = 0 temp_List = [] with(open(filename, "r")) as infile: #opening the file of raw data for line in infile: count += 1 temp_List.append(line.strip("\n")) #i add each line of infile to this temporary list if count % len(key_List) == 0: #when 7 items are added temp_dict = {} #create a temporary dictionary for key, line in zip(key_List, temp_List): #fill in dictionary key values.. temp_dict[key] = line temp_List = [] # resetting the temporary dictionary export_List.append(temp_dict) #appending dictionary to final list print(export_List) #export the list later once i get properly formatted..
现在,您可以看到在文本文件和字典示例中找到的某些条目都被视为“-”,这些条目代表了空/空值。我想将这样的值插入null而不是“-”到我的数据库中,以避免在mongo中进行批量更新查询,我觉得这可能会使数据清理/导出过程更简单,更快捷。有什么办法可以更改这些值,以便可以将它们插入为null而不是“-”将不胜感激任何解决方案,我知道可能有一个简单的答案!但这个新手将不胜感激。
免责声明:关于mongo,我是一个新手。所以我从文本文件中获取了这些数据,我正在将这些数据处理为“ python字典”格式,以便可以将其插入到我创建的集合中...
您可以在该循环中用您选择的任何值显式替换“-”: