【问题标题】:A dictionary that returns number of word and each word's lenght Python返回单词数和每个单词长度 Python 的字典
【发布时间】:2021-05-19 09:40:12
【问题描述】:
`slova=0

 a=input("Enter a sentence: ")
 str(a)

for letter in a:
    slova+=1
if letter==' ':
    slova-=1
elif letter=='.':
    slova-=1
elif letter==',':
    slova-=1
elif letter=='!':
    slova-=1
elif letter=='?':
    slova-=1

print(slova)

`所以我想制作一个程序,它将一个句子作为用户的输入,然后返回该句子有多少个单词,有多少个字符,最重要的是每个单词的长度。我考虑过使用一个字典,它使用单词名称作为键,长度作为值。这是一个只返回字母数量的程序。我也有一个返回所有字符的方法,我想以某种方式将它们与字典连接起来,以获取每个单词的字母数,但我真的不知道怎么做。示例:

我感觉很好。

字数:4

字符:18

我:1

上午:2

掉落:7

好:4

【问题讨论】:

  • 请尝试一下,然后我们可以提供帮助:)
  • 如果你的句子是“单词和字符”,输出会是什么? “words”键的值是 3 还是 5?
  • 添加你当前的代码,即使它给出了语法错误:)
  • @SpoonMeiser 输出为 5
  • len("I am felling good.") &len("I am felling good.".split(' '))

标签: python string dictionary word


【解决方案1】:
sample = "i am feeling good"

output = {}
output["word"] = len(sample.split())
output["chars"] = len(list(sample))
for elem in sample.split():
    output[elem] = len(list(elem))
print(output)

输出:

{'word': 4, 'chars': 17, 'i': 1, 'am': 2, 'feeling': 7, 'good': 4}

【讨论】:

    猜你喜欢
    • 2016-06-29
    • 2020-07-12
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 2021-04-20
    • 2012-02-02
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多