list previous or following list elements

A

antar2

Hello


Suppose I have a textfile (text1.txt) with following four words:

Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:

I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b

import re
f = open('text1.txt', 'r')
list1 = []
list2 = []
for line in f:
list1.append(line)
a = re.compile("^b")
int = 0
while(int <= list1[-1]):
int = int + 1
a_match = a.search(list1[int])
if(a_match):
list2.append(list1[int + 1])
print list2

I did not find information about addressing previous or following list
elements. So some help would be magnificent

Thanks a lot
 
T

Terry Reedy

antar2 said:
Hello


Suppose I have a textfile (text1.txt) with following four words:

I see seven. Just say 'list of words'
Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:

I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b

I believe
wordlist = open('words.txt','r').read().split('\n')
should give you the list in Python. In any case,

wordlist = ['Apple','balcony', 'cartridge',
'damned', 'paper', 'bold', 'typewriter']
for i, word in enumerate(wordlist):
if word[0] == 'b':
print(wordlist[i+1]) # 3.0
break

#prints cartridge (in 3.0)
 
N

norseman

Terry said:
I see seven. Just say 'list of words'

I believe
wordlist = open('words.txt','r').read().split('\n')

using copy/paste: yes it does
should give you the list in Python. In any case,

wordlist = ['Apple','balcony', 'cartridge',
'damned', 'paper', 'bold', 'typewriter']
for i, word in enumerate(wordlist):
if word[0] == 'b':
print(wordlist[i+1]) # 3.0
break

#prints cartridge (in 3.0)

using copy/paste: same (correct) result in python 2.5.2
for wordlist = open... AND for wordlist = [....

norseman
 
B

bearophileHUGS

Terry Reedy:
I believe
wordlist = open('words.txt','r').read().split('\n')
should give you the list in Python.

This looks better (but it keeps the newlines too. Untested. Python
2.x):

words = open("words.txt").readlines()
for i, word in enumerate(words):
if word.startswith("b"):
print words[i+1]
break

Another possibility (untested, lazy, uses less memory, probably
better):

fin = open("words.txt")
last_word = fin.next()
for word in fin:
if last_word.startswith("b"):
print word
break
else:
last_word = word
fin.close()

A note for the original poster: I suggest you to try to learn string
methods (not the string module), they are designed to avoid you to use
regular expressions most of the times, and they are faster and more
readable too. I have seen that people that learn Python coming from
Perl are often 'blind' to their existence.

Bye,
bearophile
 
B

Bruno Desthuilliers

antar2 a écrit :
Hello


Suppose I have a textfile (text1.txt) with following four words:

Apple
balcony
cartridge
damned
paper
bold
typewriter

and I want to have a python script that prints the words following the
word starting with the letter b (which would be cartridge) or
differently put, a script that prints the element following a
specified element:

def next_if(predicate, iterable):
if not hasattr(iterable, next):
iterable = iter(iterable)
for element in iterable:
if predicate(element):
yield iterable.next()


f = open('/home/bruno/text1.txt', 'r')
for elt in next_if(lambda x: x.startswith('b'), f):
print elt.strip()
f.close()

I am more experienced in Perl, and a beginner in python

I wrote a script that - of course - does not work, that should print
the element in a list following the element that starts with a b

import re
f = open('text1.txt', 'r')
list1 = []
list2 = []
for line in f:
list1.append(line)
a = re.compile("^b")
int = 0
while(int <= list1[-1]):
int = int + 1
a_match = a.search(list1[int])
if(a_match):
list2.append(list1[int + 1])
print list2

f = open('text1.txt')
lines = f.readlines()
f.close()
matchings = [
next for line, next in zip(lines, lines[1:])
if line.startswith('b')
]

print matchings
 
B

Bruno Desthuilliers

Terry Reedy a écrit :
(snip)
I believe
wordlist = open('words.txt','r').read().split('\n')
should give you the list in Python.

Or simply:
wordlist = open('words.txt').readlines()
In any case,

wordlist = ['Apple','balcony', 'cartridge',
'damned', 'paper', 'bold', 'typewriter']
for i, word in enumerate(wordlist):
if word[0] == 'b':

While this is perfectly legal, I'd rather use word.startswith('b') here.
But don't ask me why !-)
print(wordlist[i+1])

Hmmm... Guess what will happen if wordlist == ['Apple', 'balcony'] ?
 
Z

Zentrader

To be completely correct, you should allow for the possibility that
the word found is the last word in the list
for j, word in enumerate(words):
if (word.startswith("b")) and (j+1 < len(words)):
print words[j+1]
break
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top