代码之家  ›  专栏  ›  技术社区  ›  randomal

MongoDB服务器上的数据加载可以从jupyter notebook进行,但不能从脚本进行

  •  1
  • randomal  · 技术社区  · 3 年前

    我有一个存储在json文件中的数据集,需要将其上传到MongoDB服务器。如果我使用Jupyter笔记本上传数据,一切都会正常工作,但如果我使用python脚本则不会。代码完全相同。你建议如何解决这个问题?

    以下是代码:

    import pandas as pd
    import pymongo
    from pymongo import MongoClient
    import json
    import DNS
    
    # Function to upload the dialogue lines to MongoDB Server
    def prepare_dataframe():
        dialogue_edited = pd.read_json("5lines1response_random100from880_cleaned.json")
        dialogue_edited.reset_index(inplace=True)
        data_dict = dialogue_edited.to_dict("records")# Insert collection
        # To communicate with the MongoDB Server
        cluster = MongoClient()
        db = cluster['DebuggingSystem']
        collection = db['MCS_dialogue']
        collection.insert_many(data_dict)
        return collection
    
    if __name__ == '__main__':
        collection = prepare_dataframe()
    

    下面是python脚本和jupyter笔记本的截图。我正在用Visual Studio运行笔记本。

    enter image description here enter image description here

    1 回复  |  直到 3 年前
        1
  •  1
  •   Abhinav Mathur    3 年前

    代替

    if __name__ == '__main__':
        collection = prepare_dataframe()
    

    具有

    collection = prepare_dataframe()
    

    试着运行你的脚本。 __main__ 解释 here 很好