So, I have this code snippet where I read a text from a TXT-file:

file = open('test.txt', 'r')
content = file.readlines()
file.close()
print(content)

The printout:

['My name is x.\n', 'I am 45 years old.\n', '\n', 'My girlfriends name is y.\n', 'She is way too old for me.\n', 'y wears weird clothes.\n', '\n', 'Good bye.']

So the content if this TXT-file would be:

My name is x.
I am 45 years old.

My girlfriends name is y.
She is way too old for me.
y wears weird clothes.

Good bye.

What I want to is splitting the list content into three lists, by looping through it, breaking when reaching '\n' and putting each line not separated by a new line in a list. Something like:

['My name is x.\n', 'I am 45 years old.\n']
['My girlfriends name is y.\n', 'She is way too old for me.\n', 'y wears weird clothes.\n']
['Good bye.']

The reason I wan't to do this is because i wan't "My name is x" to have index one, "I am 45 years old." to have index two, "My girlfriends name is y" to have index one, and so on. Maybe there's a better way to solve this problem than to splitting the list containing all the sentences in three? I tried something like:

a, b, c = 0, 0, 0
for i in content:
  if i != '\n':
    a += 1
    b += 1
  elif i != '\n':
    b += 1
    c += 1
  else:
    c += 1
    break

However, you quickly realise my coding-skills aren't the best. :P

Recommended Answers

All 12 Replies

Seems I can't edit my post any more. The last code snippet should be:

a, b, c = 0, 0, 0
for i in content:
  if i != '\n':
    a += 1
    b += 1
    c += 1
  elif i != '\n':
    b += 1
    c += 1
  else:
    c += 1
    break

Here is one way to do this using a list of lists ...

# example data string obtained from open('test.txt', 'r').read()
data_str = """\
My name is x.
I am 45 years old.

My girlfriends name is y.
She is way too old for me.
y wears weird clothes.

Good bye."""

# make sure data_str ends with a newline character
if not data_str.endswith('\n'):
    data_str += '\n'

# use empty lines to create a list of lists
data_list = []
temp_list = []
for item in data_str.split('\n'):
    # catch empty line
    # add temp_list to data_list and reset it
    if not item:
        data_list.append(temp_list)
        temp_list = []
    else:
        temp_list.append(item)

# show each sublist
for sublist in data_list:
    print(sublist)

print('-'*50)

# show line from a particular sublist
for line in data_list[1]:
    print(line)

""" result >>>
['My name is x.', 'I am 45 years old.']
['My girlfriends name is y.', 'She is way too old for me.', 'y wears weird clothes.']
['Good bye.']
--------------------------------------------------
My girlfriends name is y.
She is way too old for me.
y wears weird clothes.
"""

Thanks a bunch!

for line in data_list[1]:
    print(line)

However, what if I only wan't to print "My girlfriends name is y." and not every line in the list?

use:

for line in data_list:
    print(line)

Python indexes start from 0 but you can add one to them when you need them or insert for example '' or [] as first (zeroth) element.

You can use partition with two new lines to separate the groups in file first and split from newlines:

inp="""My name is x.
I am 45 years old.

My girlfriends name is y.
She is way too old for me.
y wears weird clothes.

Good bye."""

sep='\n\n'
data= []
while sep:
    part,sep, inp = inp.partition(sep)
    if sep: data.append(part.split('\n'))

## last part
if '\n' in part:
    data.append(part.rstrip().split('\n'))
elif part:
    data.append([part])

print data
for ind in range(3):
    print ind,':', [info[ind] if len(info)>ind else '-' for info in data ]

Umm, but ...

for line in data_list:
    print(line)

"""
['My name is x.', 'I am 45 years old.']
['My girlfriends name is y.', 'She is way too old for me.', 'y wears weird clothes.']
['Good bye.']
"""

and

for line in data_list[1]:
    print(line)

"""
My girlfriends name is y.
She is way too old for me.
y wears weird clothes.
"""

However, I only wan't to print "My girlfriends name is y.".

print(data_list[1][0])

Thanks for all the help!

I have another question though. Say I have an int(input("blah blah")) and want to check the following:

if 2nd and 3rd number == 01
do this
elif 2nd and 3rd number == 02
do that
elif 2nd and 3rd number == 03
do something else
...
all the way to if 2nd and 3rd number == 15

How would I go ahead and do something like that?

Something like this that, maybe (couldn't use int(input("blah blah")) due to a TypeError)?

foo = input("blah blah")

if foo[2:4] == "01":
    return
elif foo[2:4] == "02":
    return
elif foo[2:4] == "03":
    return
...
elif foo[2:4] == "11":
    return
else:
    return

Not so ... good-looking code, though.

From your try I do reinteretation of your request as second and third numeric letter ie letter in string.digits. Filter out all non-digits and pick 2nd and third with slice 1:3.

import string
inp="sdfa asf as 2 lsfdjaö 5 dödgf 45 sdöf"
inp=''.join(c for c in inp if c in string.digits)
print inp
print "Second and third as number is %i." % int(inp[1:3])
int(input('blah blad'))

is correct for 3.X
for 2.X it is

int(raw_input('blah blah'))

now for your question

if sum(foo[1:3]) == 11:
    # do something
elif sum(foo[1:3]) == 1:
    # do something else
if sum(foo[1:3]) == 11:
    # do something
elif sum(foo[1:3]) == 1:
    # do something else

The "problem" is that I'm gonna have to do basically the same thing fifteen times ...

And for clearification: The input will not contain any strings, but ints - i.e. int(input(138472934728394)). (Not "blah blah". :P)

input takes input from user and you can not expect it to come in correct format.

I would use lookup table with function for each of sixteen actions, if actions are less in variation, you do not need to repeat writing that code, but use same function. Maybe you would want to include some parameters according your need to avoid using global variables.

import string
def func0():
    print "func0,",

def func1():
    print "func1,",

def func2():
    print "func2,",

def func3():
    print "func3,",

def func4():
    print "func4,",

def func5():
    print "func5,",

def func6():
    print "func6,",

def func7():
    print "func7,",

def func8():
    print "func8,",

def func9():
    print "func9,",

def func10():
    print "func10,",

def func11():
    print "func11,",

def func12():
    print "func12,",

def func13():
    print "func13,",

def func14():
    print "func14,",

def func15():
    print "func15,",

def func16():
    print "func16,",


inp="sdfa asf as 2 lsfdjaö 1 dödgf 45 sdöf"
inp=''.join(c for c in inp if c in string.digits)
print  inp
print  "Second and third as number is %i." % int(inp[1:3])

# function lookup table
funcs=(func0,func1,func2,func3,func4,func5,func6,func7,
       func8,func9,func10,func11,func12,func13,func14,func15,func16)

for action in [int(inp[1:3])]+range(17):
    if action in range(len(funcs)):
        funcs[action]()
    else:
        "Number out of range:",action
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.