简体   繁体   中英

Text file to dictionary in python

I have a txt file of this type, grouping related messages, am looking for a way to make a dictionary out of this that I can use in a python script.

Edit:
The script I want should loop through these messages and create a dictionary with the first word in each sentence as the key and the other part as the value.

My implementation right now does not have any errors, just that the output list is full of duplicated records.

from Doe
message Hello there
sent_timestamp 33333333334
message_id sklekelke3434
device_id 3434


from sjkjs
message Hesldksdllo there
sent_timestamp 3333sdsd3333334
message_id sklekelksde3434
device_id 34sd34


from Doe
message Hello there
sent_timestamp 33333333334
message_id sklekelke3434
device_id 3434

here is my code as of now

lines = []
records = {}

f = open('test1.txt', 'r+')
for line in f.readlines():
    if len(line.split()) != 0:
       key_name, key_value = line.strip().split(None, 1)
       records[key_name] = key_value.strip()
    lines.append(records)
f.close()

Like @Michael Butschner said in their comment, it's kind of hard to tell what you're looking for, but here's an idea that you can use.

records = []

# used with since your question tags python-3.x
with open('test1.txt', 'r+') as f:
    messages = f.read().split("\n\n\n")

    for message in messages:
        message = message.split("\n")
        records.append({
            "from": message[0][5:],
            "message": message[1][8:],
            "sent_timestamp": message[2][15:],
            "message_id": message[3][11:],
            "device_id": message[4][10:]
        })

Here is what that records list looks like, using the json package to stringify it:

[
  {
    "from": "Doe",
    "message": "Hello there",
    "sent_timestamp": "33333333334",
    "message_id": "sklekelke3434",
    "device_id": "3434"
  },
  {
    "from": "sjkjs",
    "message": "Hesldksdllo there",
    "sent_timestamp": "3333sdsd3333334",
    "message_id": "sklekelksde3434",
    "device_id": "34sd34"
  },
  {
    "from": "Doe",
    "message": "Hello there",
    "sent_timestamp": "33333333334",
    "message_id": "sklekelke3434",
    "device_id": "3434"
  }
]

Without clarification as to what exactly you're expecting, I hope this helps you a bit with whatever you're working on:D.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM