Reputation: 5
I'm trying to print the first x amount of capital letters and I'm not sure how to make it not print the right amount of occurrences, atm mine is just printing all of the capital letter words in the string rather than e.g 5
def first_x_capitalised_words(filename, x):
wordfile = open(filename)
text_str = wordfile.read()
words = text_str.split()
i = 0
result = ''
while i < len(words):
word = words[i]
if word.istitle():
result += word + ' '
i+=1
wordfile.close()
return result
Upvotes: 0
Views: 42
Reputation: 36882
You can decrement x
every time you append a new word, then exit the loop when x
hits zero
while i < len(words) and x > 0:
word = words[i]
if word.istitle():
result += word + ' '
x -= 1
i+=1
There's a lot you can do to bring this code from C-style to something more pythonic
Rather than explicitly open and close the file, you can read the contents in a context manager with/as block, which means you don't have to explicitly close the file later
with open(filename) as word_file:
words = word_file.read().split()
You can use a for-each to iterate over the words rather than an index i
for word in words:
...
Your result
will have a trailing ' '
, and you are creating a lot of intermediate strings, instead you could create a list of strings, then use str.join
to stick them all together with spaces in between
results = []
# then inside the loop
results.append(word)
# then at the end
return ' '.join(results)
The final program would then look like this:
def first_x_capitalised_words(filename, x):
with open(filename) as word_file:
words = word_file.read().split()
results = []
for word in words:
if x == 0:
break
if word.istitle():
x -= 1
results.append(word)
return ' '.join(results)
Upvotes: 1
Reputation: 66
You can create a dummy variable an increment it until it equals that input. Then you can exit the loop. If you need more info let me know.
Also this is an example I just made with the input being a String:
someString = "Hello it is Some Strings blah blah Blah"
caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
isWord = False
word = ""
for i in someString:
if i in caps:
isWord = True
if isWord:
word += i
if i == " " and isWord == True:
print(word)
word = ""
isWord = False
Upvotes: 0
Reputation: 612
If I just wanted to modify your solution I would do something like this:
read=0 # the number of words you already read
i = 0
result = ''
while i < len(words):
word = words[i]
if word.istitle():
result += word + ' '
read+=1
if read==x: # exit the loop when x words were read
break
i+=1
However, I'd rather simplify your solution so that you wouldn't even need i
and indexing at all.
read=0
for word in words:
if word.istitle():
result+=word+' '
read+=1
if read==x:
break
This way, your solution becomes cleaner and you get rid of len(words)
and i
Upvotes: 0