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

(ignore this response, accidental post)

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.

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

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

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".

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
Member Avatar for leegeorg07

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

Thanks the last two worked fine.

Thats just what i wanted thanks alot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.