2012-11-03 19 views
6

我正在寫出一個小的代碼片斷,它抓取所有以python中的大寫字母開頭的字母。這裏是我的代碼檢測以字符串中的大寫字母開頭的所有單詞的代碼

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

現在,當我運行上面的代碼。我期待該列表將包含字符串中的所有元素,因爲它中的所有單詞都以大寫字母開頭。 但這裏是我的輸出:

@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 

回答

9

你只是在評估一次,所以你得到的真正的列表,並只追加的最後一個項目。

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

for word in words: 
    if word[0].isupper(): 
     list1.append(word) 
1

你可以採取filter功能的優勢:

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

這也是在刪除答案中提出的,但它有一個問題:它不能處理CamelCase,它以大寫字母開頭, 'CamelCase'.istitle()'是假的。與「ALLCAPS」類似。 – DSM

0

我寫了下面的Python代碼片段以大寫字母開始的話存儲到字典作爲關鍵並沒有出現在這本字典中作爲對鑰匙的價值。

#!/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"[A-Z]\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)) 

在上面的代碼中,我顯示了兩種方法,數組索引來檢查大寫的開始字母和使用正則表達式。以上代碼的性能或簡單性的改進建議是值得歡迎的

相關問題