【发布时间】:2015-11-15 14:07:32
【问题描述】:
这是我的第一篇文章,我刚刚开始使用 Python 编程。
所以,对于一个作业,我必须分析一个文本,通过说明它包含的单词数,然后说明有多少个单词有 n 个字符。
这是我想出的,但是我的 n 字符数是有限的..并且必须有一个更优雅的方法来做到这一点。
我希望输出类似于:
"文本包含:
3 个单词,4 个字符
n 个单词,n 个字符"
理论上我知道“怎么做”,但是不知道怎么用代码来做。
-
sort d[i]len(d[i])
2.将相同长度的单词存储在一个变量中
text = input("Type your text: ")
words = text.split()
number_of_words = len(words)
print("Result:\nthe text contains", number_of_words, "words")
d = {}
i = 0
for words in text.split():
d[i] = words
i += 1
n = 0
p = 0
q = 0
for i in d:
if len(d[i]) == 1:
n += 1
elif len(d[i]) == 2:
p += 1
elif len(d[i]) == 3:
q += 1
print(n, "words with 1 character")
print(p, "words with 2 characters")
print(q, "words with 3 characters")
【问题讨论】:
-
计算字典中每个字符串的字符数是什么意思?输入和输出示例?
-
输入是文本。输出例如是:“文本包含 n 个带有 x 个字符的单词和 n 个带有 y 个字符的单词”
标签: python sorting dictionary text analysis