Python计算字典中每个字符串的字符数
这是我的第一篇文章,我刚刚开始Python编程 因此,对于一个作业,我必须分析一篇文本,先说明它包含的单词数量,然后说明有多少单词有n个字符 这就是我所想到的,但是我的n对于字符的数量是有限的,必须有一个更优雅的方法来做到这一点 我希望输出类似于: “案文包括: 3个单词,4个字符 n个单词加n个字符“ 理论上我知道如何去做,但不知道如何使用代码去做Python计算字典中每个字符串的字符数,python,sorting,dictionary,text,analysis,Python,Sorting,Dictionary,Text,Analysis,这是我的第一篇文章,我刚刚开始Python编程 因此,对于一个作业,我必须分析一篇文本,先说明它包含的单词数量,然后说明有多少单词有n个字符 这就是我所想到的,但是我的n对于字符的数量是有限的,必须有一个更优雅的方法来做到这一点 我希望输出类似于: “案文包括: 3个单词,4个字符 n个单词加n个字符“ 理论上我知道如何去做,但不知道如何使用代码去做 按len(d[i]) 2.将长度相同的单词存储在变量中 text = input("Type your text: ") words = tex
按len(d[i])
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")
我也是python新手,但根据您的要求,这可能会奏效
text = raw_input("Type your text: ")
words = text.split()
print words
for i in words:
print 'string=',i , ', length=',len(i)
从用户处获取输入并按空格分割,然后循环列表
单词
,并使用len函数获取字符串长度,而不是单独计算字符串长度考虑内置python函数sort()
(请参阅:)
对于d
,您可能希望使用列表而不是字典,因为键只是一个int索引
d = text.split()
d.sort(key=len(d[i]))
charcount = 1
prev_i = 0
for i in range(len(d)):
if len(d[i]) > len(d[i-1]):
print i-prev_i, "words with %d characters" % charcount
prev_i = i
charcount += 1
希望这会有所帮助:)
最容易使用列表理解和内置列表方法:
text = raw_input('type:' )
type:adam sam jessica mike
lens = [len(w) for w in text.split()]
print [lens.count(i) for i in range(10)]
[0, 0, 0, 1, 2, 0, 0, 1, 0, 0]
在字典中计算每个字符串的字符是什么意思?输入和输出示例?输入为文本。例如,输出为:“文本包含n个x字符的单词和n个y字符的单词”
text = raw_input('type:' )
type:adam sam jessica mike
lens = [len(w) for w in text.split()]
print [lens.count(i) for i in range(10)]
[0, 0, 0, 1, 2, 0, 0, 1, 0, 0]