2012-11-03 3 views
6

파이썬에서 대문자로 시작하는 모든 문자를 가져 오는 작은 스 니펫을 작성하고 있습니다. 여기 내 코드가문자열에서 대문자로 시작하는 모든 단어를 검색하는 코드

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

위의 코드를 실행할 때. Im은 문자열에있는 모든 단어가 대문자로 시작하기 때문에 문자열의 모든 요소를 ​​포함 할 것으로 기대합니다. 그러나 여기 내 출력입니다 :

@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() ] 

또는

당신은 filter 기능을 활용할 수
for word in words: 
    if word[0].isupper(): 
     list1.append(word) 
1

: 나는 키와 사전에 단어를 시작하는 대문자를 저장하기 위해 다음과 같은 파이썬 코드 조각을 작성했습니다

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

삭제 된 답변에서도 제안되었지만 대문자로 시작하는'CamelCase'는 처리 할 수 ​​없지만 ' 'CamelCase'.stititle()'은 거짓입니다. 'ALLCAPS'와 비슷합니다. – DSM

0

이 사전에 키에 대한 가치로 외양이 없다. 위의 코드에서

#!/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)) 

, 나는 대문자로 시작 문자과 정규 표현식을 사용하여 확인하는 두 가지, 배열 인덱스를 표시. 위의 코드가 성능 향상을 위해 또는 더 간단하게 사용할 수있는 제안을 환영합니다.

관련 문제