【问题标题】:How to put only words that start with an uppercase letter in the dictionary?如何在字典中只输入以大写字母开头的单词?
【发布时间】:2013-10-28 08:35:03
【问题描述】:

我有一个文本文档。我想从这个文档中编译一个字典(DICT)。字典只能包含所有以大写字母开头的单词。 (单词是否在句首无关紧要)

到目前为止,我已经这样做了: 顺便说一句,我必须使用 for 循环split 函数来解决这个问题

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. 如何验证我是否正确制作了字典?

【问题讨论】:

  • 如何验证?你为你的代码编写一个单元测试。
  • 我是新手。我不知道如何编写“提取首字母大写”的代码
  • @user2799617:这里有很多努力,没必要这么……脾气暴躁。您是否从过去的课程中吸取了教训?

标签: python dictionary uppercase


【解决方案1】:

使用s.isupper() method 测试字符串是否为大写。您可以使用索引来选择第一个字符。

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

if word[0].isupper():

如果您想要一种快速且 Python 的方法,请使用 collections.Counter() object 进行计数,然后拆分所有空格以删除换行符:

from collections import Counter

counts = Counter()

for line in lines: # lines is the text without line breaks 
    counts.update(word for word in line.split() if word[0].isupper())

这里,word.split() 不带参数拆分所有空格,删除行首和行尾的所有空格(包括换行符)。

【讨论】:

  • 这是一个不错的,但我们在学期初期,我想,收藏还不是一个话题;)。所以提交这个答案时要小心:)。
【解决方案2】:
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) 复杂度。但是这个变种有点“pythonic”。

【讨论】:

    【解决方案3】:

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

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

    要验证这一点,您可以使用any 方法:

    any(word[0].islower() for word in DICT.keys())
    

    应该返回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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多