Code to detect all words starting with a capital letter in a string

I am writing a small fragment that captures all letters starting with a capital letter in python. Here is my code

def WordSplitter(n): list1=[] words=n.split() print words #print all([word[0].isupper() for word in words]) if ([word[0].isupper() for word in words]): list1.append(word) print list1 WordSplitter("Hello How Are You") 

Now when I run the above code. I expect this list to contain all the elements from the string, since all words in it begin with a capital letter. But here is my conclusion:

 @ubuntu:~/py-scripts$ python wordsplit.py ['Hello', 'How', 'Are', 'You'] ['You']# Im expecting this list to contain all words that start with a capital letter 
+6
source share
3 answers

You only evaluate it once, so you get a True list, and it only adds the last item.

 print [word for word in words if word[0].isupper() ] 

or

 for word in words: if word[0].isupper(): list1.append(word) 
+9
source

You can use the filter function:

 l = ['How', 'are', 'You'] print filter(str.istitle, l) 
+1
source

I wrote the following python snippet to store start words as a word as a dictionary and without it appearing as a value in this dictionary against the key.

 #!/usr/bin/env python import sys import re hash = {} # initialize an empty dictinonary for line in sys.stdin.readlines(): for word in line.strip().split(): # removing newline char at the end of the line x = re.search(r"[AZ]\S+", word) if x: #if word[0].isupper(): if word in hash: hash[word] += 1 else: hash[word] = 1 for word, cnt in hash.iteritems(): # iterating over the dictionary items sys.stdout.write("%d %s\n" % (cnt, word)) 

In the above code, I showed both ways, an array index, to check the capital letter of the beginning and using a regular expression. A welcome suggestion to improve the above code for performance or for simplicity is welcome

0
source

All Articles