1

this is one of my exercises in Python ebook. I just wonder if it is possible to use WHILE instead of FOR. Thanks for your help

#Ask the user to enter a regular expression #count the number of lines that matched the regular expression.

My code

x= input('Enter a regular expression.') 
file = open('mbox-short.txt') 
count = 0  
for line in file: line=line.rstrip()
  if re.search('\\b' + x + '\\b', line):
    count=count+1
print (count)

4 Answers 4

2

If you really want to step it up a notch, leverage that fact that True and False sum as 1 and 0. This gets rid of explicit for and while completely.

import re
x = input('Enter a regular expression.')
my_regex = '\\b' + x + '\\b'
with  open('mbox-short.txt') as f:
    count = sum(bool(re.search(my_regex, line)) for line in f)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the while loop as below to perform the same task as below,

import re
x = input('Enter a regular expression.')
fileHandler = open('tmp.txt')
count = 0
while True:
    line = fileHandler.readline()
    if not line:
        break
    if re.search('\\b' + x + '\\b', line):
        count += 1
print (count)

6 Comments

Your second example is missing the loop.
I added the second example just to give an idea to achieve the same or rather a better way, without using for or while
It only reads a single line. Its not the same thing.
Yes, it does. I added it to give some extra information. @tdelaney I will remove it as the question is loops specific only.
it worked. I tried changing the condition a little bit, but the result wasn't same (my one was incorrect). Can you help me to explain? while True: if not fileHandler.readline(): break elif re.search('\\b' + x + '\\b', fileHandler.readline()): count += 1
|
0
x= input('Enter a regular expression.')
file = open('mbox-short.txt') 
count = 0
while(re.search('\\b' + x + '\\b', line)):
   count = count+1
print(count)

This will work I think so.

4 Comments

This will raise a "NameError: name 'line' is not defined" error.
What is the condition of this program? I think there is need to change in condition
This doesn't work. Not only do you not read the file, you just loop on the same condition over and over.
I tried to fix "line is not defined" with while(re.search('\\b' + x + '\\b', open("mbox.txt").read())). But it still didn't work.
0

try

x= input('Enter a regular expression.')
file = open('mbox-short.txt') 
count = 0
temp=0
lines=file.readlines()
while True:
    if re.search('\\b' + x + '\\b', lines[temp]):
        count=count+1
    if temp==len(lines)-1:
        break
    temp=temp+1
print(count)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.