I have a .csv document with 16 rows. Each row starts with letters, in this case with a
or b
.
The outer for loop will check, line by line, the first letter. If row x
starts with b
, the second for-loop will count all rows until b
occurs again.
Example:
1. a
2. a
3. a
4. a
5. b
6. a
7. a
8. a
9. a
10.a
11.a
12.a
13.b
14.a
…
b
is found in line 5, next in row 13. There are 7 rows between…
That's my script to count rows from line 5 to line 13:
"Verschachtelteitertools"
import itertools
import re
df = open('zeilen.csv')
for i, line in enumerate(df):
#print(i,line)
if re.search('b',line):
#print(i,line)
k = i+1
count = 1
#print(k)
for line in itertools.islice(df,k):
if bool(re.search('b',line)) == False:
count=count+1
lineX = count
print(lineX)
I have chosen itertools.islice()
to count rows between b
(1st occurrence) and b
in line 13. k
should represent the starting Point of the inner loop.
import itertools import re
df = open('zeilen.csv') for i, line in enumerate(df): #print(i,line) if re.search('b',line): #print(i,line) k = i+1 count = 1 #print(k) for line in itertools.islice(df,k):
if bool(re.search('b',line)) == False: count=count+1 lineX = count print(lineX)
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.