Home > Back-end >  How do I split a txt file based on a condition of a certain element in in a certain order list (Pyth
How do I split a txt file based on a condition of a certain element in in a certain order list (Pyth

Time:05-06

So I need to split a txt file into a dictionary. The txt file could look like this:

Keyone -2
key-two 1
Key'Three -3
Key four-here 5

I think I would need to check the list reversed to check if the second to last element is either a " " or a "-", but since there could be "-" between the words in the string, I'am a bit confused as to how to approach this.

I need the dict to look like [str(key); int(value)]

My tries so far, lookes like:

`

for line in file
  a=line.split()
  value = a[-1]
  key=line[0:-2]
  key=key.replace("-","")

`

CodePudding user response:

try the following code:

# Define input
txt = "Keyone -2\nkey-two 1\nKey'Three -3\nKey four-here 5"
print(txt)

# Split the text by newlines
lines = txt.split('\n')
print(lines)

# Iterate over all lines
d = {}
for line in lines:
    line.split(' ')
    # The key is  element after the last space
    key = "".join(line[:-1])
    # The value is everything before the first space
    value = line[-1]
    # Assuming it can only be an integer
    value = int(value)
    d[key] = value
print(d)

CodePudding user response:

with open ("text.txt") as f:
    for i in f:
        a=i.split()
        value=a[-1]
        key=i[0:-2]
        #print(type(key))
        key=key.replace("-","")
        d[key[0:-1]]=value
        
print(d)

CodePudding user response:

The following is the answer using regex:

import re

data_to_parse = """
Keyone -2
key-two 1
Key'Three -3
Key four-here 5
"""

data_to_parse = data_to_parse.splitlines()

pattern = " -?\d"
new = {}

for line in data_to_parse:
    if re.findall(pattern, line):
        x = re.findall(pattern, line)
        #print(line[line.find(x[0]) - 1:])
        new[line[:line.find(x[0])].strip()] = line[line.find(x[0]):].strip()    
print(new)

See the output:

enter image description here

EDITED:

If the values needs to be an integer, please change the line as following:

new[line[:line.find(x[0])].strip()] = int(line[line.find(x[0]):].strip())

So that the output is going to be below:

enter image description here

  • Related