【问题标题】:How to i extract a particular parameter and it's data from multiple text files?如何从多个文本文件中提取特定参数及其数据?
【发布时间】:2021-12-17 14:58:45
【问题描述】:

假设我有多个文件,例如 file1、file2 和 file3,并且包含以下数据:

文件1:

{"status":"succes","message":"User Found","error_code":"0","data":{"phone":0,"name":"Sanju Mehra","gender":"","tob":"","dob":"","pob":"","email":"sanjumehra.palasi@gmail.com"}

文件2:

{"status":"succes","message":"User Found","error_code":"0","data":{"phone":0,"name":"Anil Kumar","gender":"","tob":"","dob":"","pob":"","email":"kumaranil12462@gmail.com"}

文件3:

{"status":"succes","message":"User Found","error_code":"0","data":{"phone":89XXXXXXXX,"name":"Ashish Chauhan","gender":"male","tob":"12:30","dob":"10\/18\/94","pob":"ambala, haryana","email":"ashishchauhan1810@gmail.com"}

我想从这些多重文件中提取姓名和电话号码,我实际上想提取电话号码的数据和在名称参数上输入的数据。

你能告诉我我可以用哪些方法来做到这一点吗?

【问题讨论】:

  • 看起来你有 JSON 文件。使用模块json

标签: python json extract text-extraction notepad


【解决方案1】:

文件中的数据看起来像dictionary format。那么答案如下

import os,sys        

ws=r"C:\Users\xx\Desktop\dd"
for root,dirs,files in os.walk(ws):
    for file1 in files:
        file_path=os.path.join(root,file1)

        file2 = open(file_path, "r", encoding="utf8") 

        data_string=file2.read()
        #Then the phone number is    
        phone_number=data_string['data']['phone']    
        #    Then the name is
        name=data_string['data']['name']    
        #like above you can access all keys and value from dictionary

【讨论】:

  • 您好,感谢您编写代码,当我在 pycharm 中运行它时,我似乎收到以下错误。声明预期,发现 Py:DEDENT 如果我有 2000 多个文件并且想将所有提取的数据转移到一个新文件中,你能告诉我该怎么办吗?谢谢!
  • 是否所有文件都具有相同的数据语法并且每个文件只有一个字典?对于您的 Py:DEDNT 解决方案,stackoverflow.com/questions/47776315/…
  • 是的,所有文件似乎都有相同的语法,只是数据可能会有所不同。
  • 谢谢你,你能否为多个文件编写代码,它们的文件名是从 0 到 4000 的数字
  • 我的答案已更新。如果您得到答案,请接受。
猜你喜欢
  • 1970-01-01
  • 2022-07-20
  • 2021-12-07
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 2018-09-11
相关资源
最近更新 更多