我正在写出一个小片段,该片段抓起所有以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 %sn" % (cnt, word))
在上面的代码中,我以两种方式显示了以检查大写的开始字母并使用正则表达式的数组索引。欢迎对上述绩效或为简单起见的上述代码的改进建议