0

Hi i have a program that currently reads in the contents of a file and stores it in a string. Some of the files are quite large so speed is quite important. I want to print out the words that begin with capital letters and was wondering how i could achieve this. I've been experimenting with re.search but i'm not sure this is what i want.

I'd appreciate any help

Many thanks

6
Contributors
8
Replies
11
Views
8 Years
Discussion Span
Last Post by akkkk
0

What you need to do is read one word at a time from the file and check that word for capitalization. Here's an example:

word = ""
char = fobj.read(1)
while char:
     if char == " ":
         if word.istitle():
             print word
         word = ""
    else:
         word += char
    char = fobj.read(1)

Note: I haven't tested this.

0

What you need to do is read one word at a time from the file and check that word for capitalization. Here's an example:

word = ""
char = fobj.read(1)
while char:
     if char == " ":
         if word.istitle():
             print word
         word = ""
    else:
         word += char
    char = fobj.read(1)

Note: I haven't tested this.

Hi, thank you for your reply, when i tested your code it was only picking up the first word which began with a capital letter.

Would it better to find capital letters in the string and then count the characters to whitespace to find the words?

Regards

0

Sure.. Whatever actually works is probably fine. You can always optimize from there.

0

Split the string on whitespace and check the first character of each word. You can use >= "A", <="Z"; or check that the ord of the character is within the capital letter range; or create a list of capital letters and use "if the first letter is in the list".

0

Did you tried this??

>>>s="No one can be told how good Python is, you have to See it for your self"
>>> for x in s.split():
...     if (x[0].isupper()):
...             print x
... 
No
Python
See
0

Did you tried this??

>>>s="No one can be told how good Python is, you have to See it for your self"
>>> for x in s.split():
...     if (x[0].isupper()):
...             print x
... 
No
Python
See

yeah i was just about to suggest .isupper()
but i made a function to make it easier to use again and again:

def x_is_upper(x):
    if x[0].isupper():
        print x
0

Thanks the last two worked fine.

Thats just what i wanted thanks alot.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.