Python计算字典中每个字符串的字符

时间:2015-11-15 14:07:33

标签: python sorting dictionary text analysis

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

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

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

我希望输出类似于:

“该文字包含:

包含4个字符的3个单词

n个带有n个字符的单词“

我从理论上知道“怎么做”,但不知道如何使用代码来做到这一点。

  1. sort d[i] len(d[i])
  2. 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")
    

4 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

考虑内置的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 :(得分:0)

希望这会有所帮助:)

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 :(得分:0)

最简单的方法是使用列表推导和内置列表方法:

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]