Need help with the following:
- Reading from one string until another specified string.
- Merging 2 strings on separate lines onto 1 line I tried strip() and this was not successful.
- Create 2 separate arrays from the text provided.
Given:
JavaScript
x
7
1
Cat Chores
2
Get
3
cat food.
4
Dog Chores
5
Get
6
dog food. Walk Dog.
7
Desired output:
JavaScript
1
3
1
Cat Chores
2
Get cat food.
3
These sentences are separated because they will be put in an array.
JavaScript
1
3
1
Dog Chores
2
Get dog food. Walk Dog.
3
Final output:
JavaScript
1
3
1
cat_chores = [Get cat food.]
2
dog_chores = [Get dog food. , Walk Dog]
3
Here is my code:
JavaScript
1
21
21
1
# Remove whitespace and reformat the file
2
with open('chores.txt',"r") as f:
3
text = input.read()
4
text = [lines.strip() for lines in text]
5
6
with open('chores.txt',"w") as f:
7
f.writelines(text)
8
f.close
9
10
# Re-open the file to create the arrays.
11
with open('chores.txt',"r") as f:
12
text = input.read()
13
14
if "Cat Chores" in text:
15
print (line,end='')
16
print(next(input),end='')
17
18
if "Dog Chores" in text:
19
print (line,end='')
20
print(next(input),end='')
21
Advertisement
Answer
Try this:
JavaScript
1
19
19
1
chores = {}
2
action = ''
3
with open('chores.txt', 'r') as f:
4
for line in f.read().splitlines():
5
line = line.strip() # your original data had trailing spaces. this is to remove them
6
if 'Chores' in line: # check if line is a grouping
7
current_chore = line
8
chores[current_chore] = []
9
elif len(line.split(' ')) == 1: # check if line is an action
10
action = line + ' '
11
continue
12
else:
13
chores[current_chore].append(action + line)
14
action = ''
15
16
with open('chores.txt', 'w') as f:
17
f.write(str(chores))
18
f.close
19
It will output:
JavaScript
1
2
1
{'Cat Chores': ['Get cat food.'], 'Dog Chores': ['Get dog food. Walk Dog.']}
2
This assumes that a grouping always contains ‘Chores’, action is always 1 word, and outputs a string of a dictionary. My version doesn’t separate ‘Get dog food.’ and ‘Walk Dog.’ but if you want that you can add a split() on ‘. ‘ and handle it. The formatting of your input data is horrible and really shouldn’t be used as is.