Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用于检测字符串中以大写字母开头的所有单词的代码_Python - Fatal编程技术网

Python 用于检测字符串中以大写字母开头的所有单词的代码

Python 用于检测字符串中以大写字母开头的所有单词的代码,python,Python,我正在编写一个小片段,其中包含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) prin

我正在编写一个小片段,其中包含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() ]


您可以利用
过滤器
功能:

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

在上面的代码中,我展示了两种方法:检查大写起始字母的数组索引和使用正则表达式。欢迎对上述代码的性能或简单性提出任何改进建议

这也是在删除的答案中提出的,但它有一个问题:它无法处理以大写字母开头的
CamelCase
,但
'CamelCase'.istitle()
为假。与
ALLCAPS类似。
#!/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))