我有一份文本文件。我想根据这份文件编一本词典。词典只能包含所有以大写字母开头的单词。(这个词是否在句首并不重要)
到目前为止,我已经做到了: 顺便说一下,对于这个问题,我必须使用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
但我想这只会把我课文中所有的单词都编成词典。在
使用^{} method 测试字符串是否为大写。您可以使用索引来选择第一个字符。在
因此,要测试第一个字符是否为大写,请使用:
如果您想要快速的python方法,请使用^{} object 进行计数,并在所有空白处拆分以删除换行符:
^{pr2}$在这里,
word.split()
不带参数将对所有空白进行拆分,删除行开始和结尾处的所有空白(包括换行符)。在groupby
可能比手动循环效率低,因为它需要sorted iterable执行排序,并且排序是O(NlogN)复杂的,在手动循环的情况下,超过O(N)的竞争性。但这个变种有点“Python”。在您可以使用前面提到的使用^{} 函数检查单词是否以大写字母开头,并将其包含在
if else
语句之前。在要验证这一点,可以使用^{} 方法:
^{pr2}$它应该返回
False
。你可以选择asset这个。在为了使一切变得更好,可以使用defaultdict
相关问题 更多 >
编程相关推荐