如何在字典中只把以大写字母开头的单词放在字典里?

2024-09-28 01:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份文本文件。我想根据这份文件编一本词典。词典只能包含所有以大写字母开头的单词。(这个词是否在句首并不重要)

到目前为止,我已经做到了: 顺便说一下,对于这个问题,我必须使用for循环分割函数

DICT = {}

for line in lines: # lines is the text without line breaks 
    words = line.split(" ")
    for word in words:
        if word in DICT:
            DICT[word] += 1
        else:
            DICT[word] = 1

但我想这只会把我课文中所有的单词都编成词典。在

  1. 我怎样才能只选择以大写字母开头的单词?在
  2. 我如何核实我是否正确地编了这本词典?在

Tags: 文件函数inforisline大写字母单词
3条回答

使用^{} method测试字符串是否为大写。您可以使用索引来选择第一个字符。在

因此,要测试第一个字符是否为大写,请使用:

if word[0].isupper():

如果您想要快速的python方法,请使用^{} object进行计数,并在所有空白处拆分以删除换行符:

^{pr2}$

在这里,word.split()不带参数将对所有空白进行拆分,删除行开始和结尾处的所有空白(包括换行符)。在

from itertools import groupby
s = "QWE asd ZXc vvQ QWE"
# extract all the words with capital first letter
caps = [word for word in s.split(" ") if word[0].isupper()]  
# group and count them
caps_counts = {word: len(list(group)) for word, group in groupby(sorted(caps))}

print(caps_counts)

groupby可能比手动循环效率低,因为它需要sorted iterable执行排序,并且排序是O(NlogN)复杂的,在手动循环的情况下,超过O(N)的竞争性。但这个变种有点“Python”。在

您可以使用前面提到的使用^{}函数检查单词是否以大写字母开头,并将其包含在if else语句之前。在

if word[0].isupper():
    if word in DICT:
        DICT[word] += 1
    else:
        DICT[word] = 1

要验证这一点,可以使用^{}方法:

^{pr2}$

它应该返回False。你可以选择asset这个。在

为了使一切变得更好,可以使用defaultdict

from collection import defaultdict

DICT = defaultdict(int)
for line in lines:
    words = line.split(" ")
    for word in words:
        if (word in DICT) and (word[0].isupper()):
            DICT[word] += 1

相关问题 更多 >

    热门问题