【问题标题】:Python counting characters of each string in a dictionaryPython计算字典中每个字符串的字符
【发布时间】:2015-11-15 14:07:32
【问题描述】:

这是我的第一篇文章,我刚刚开始使用 Python 编程。

所以,对于一个作业,我必须分析一个文本,通过说明它包含的单词数,然后说明有多少个单词有 n 个字符。

这是我想出的,但是我的 n 字符数是有限的..并且必须有一个更优雅的方法来做到这一点。

我希望输出类似于:

"文本包含:

3 个单词,4 个字符

n 个单词,n 个字符"

理论上我知道“怎么做”,但是不知道怎么用代码来做。

  1. 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


【解决方案1】:

考虑内置的python函数sort()(参见:Python docs)。

您可能希望对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

【讨论】:

    【解决方案2】:

    希望这会有所帮助:)

    text = raw_input("Type your text: ")
    words = text.split()
    
    
    print ("Result:\nthe text contains" + str(len(words)) + "words")
    
    # Using a list instead of a dictionary
    d = []
    
    # Loop over the list, word by word
    for i in words:
            # Exception if full stop found. Probably should filter out other characters as well to be safe. (cause user input)
        if i.find('.')!=-1:
            # Remove fullstops
            q = i.replace(".", "")
            # Add word to the end of our list
            d.append(q)
        else:
            # If no punctuation encountered, just add the word
            d.append(i)
    
    # test out
    print d
    
    # The rest seems legit enough
    

    【讨论】:

      【解决方案3】:

      最容易使用列表推导和内置列表方法:

      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]
      

      【讨论】:

        【解决方案4】:

        我也是 python 新手,但根据您的要求,这可能有效。

         text = raw_input("Type your text: ") 
         words = text.split()
         print words
         for i in words:
             print 'string=',i , ', length=',len(i)
        

        从用户那里获取输入并用空格分割然后遍历列表words并使用len函数来获取字符串长度而不是单独计算它们

        【讨论】:

          猜你喜欢
          • 2022-07-08
          • 2023-03-03
          • 2014-04-17
          • 1970-01-01
          • 2016-07-22
          • 1970-01-01
          • 2022-11-17
          • 2019-01-30
          • 1970-01-01
          相关资源
          最近更新 更多