繁体   English   中英

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

[英]Python counting characters of each string in a dictionary

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

因此,对于一项作业,我必须分析一个文本,说明其包含的单词数,然后说明具有n个字符的单词数。

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

我希望输出是这样的:

“文本包含:

3个字和4个字符

n个单词和n个字符”

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

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

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

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

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

考虑内置的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

希望这会有所帮助:)

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

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

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM