簡體   English   中英

用於檢測以字符串中的大寫字母開頭的所有單詞的代碼

[英]Code to detect all words that start with a capital letter in a string

我正在寫一個小片段,它抓住所有以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

你只評估它一次,所以你得到一個True列表,它只附加最后一項。

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

要么

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

您可以利用filter功能:

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

我編寫了以下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))

在上面的代碼中,我展示了兩種方式,數組索引來檢查大寫的起始字母和使用正則表達式。 對於上述代碼的性能或簡單性的任何改進建議都是受歡迎的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM