谢谢大家在前一部分的帮助。我现在已经完成了。 然而,稍微改变标题和重新措辞问题我现在说这是我的代码。
s = raw_input("Enter your text: ")
longestWord = max(s.split(), key=len)
k = list(s)
count = len(k)
wordsOver = []
over = count - 140
def numLen(s, n):
return sum(1 for x in s.split() if len(x) >= n)
for x in s.split():
if len(x) >= n:
wordsOver.insert(0, x)
val = numLen(s, 7)
if count > 140:
print ("Sorry, that is more than 140 characters.")
print ("You had a total of " + str(count) + " characters.")
print ("That's " + str(over) + " over the max allowed.")
print ("You're longest word was, " + longestWord)
print ("There are " + str(val) + " words over 7 characters.")
print ("They were:")
print (wordsOver)
print ("You may want to consider changing them for shorter words.")
else:
print ("That's short enough!")
所以现在我正在寻找的是为什么显示结束的单词不起作用,为什么以及如何解决它。顺便说一句,它有点帮助,这就是“有点破坏”这个词。
答案 0 :(得分:1)
欢迎来到SO!
我认为这就是你想要做的。在您的numLen函数中,添加到列表时需要使用append()
而不是insert()
。这是因为当使用insert时,你没有递增索引,因此每次在索引0处插入时,都会覆盖已存在的任何值。附加功能可以找到列表末尾的位置,并将传递给它的内容放到最后。
s = raw_input("Enter your text: ")
longestWord = max(s.split(), key=len)
k = list(s)
count = len(k)
wordsOver = []
over = count - 140
def numLen(s, n):
for x in s.split():
if len(x) >= 7:
wordsOver.append(x)
return len(wordsOver)
val = numLen(s, 7)
if count > 140:
print ("Sorry, that is more than 140 characters.")
print ("You had a total of " + str(count) + " characters.")
print ("That's " + str(over) + " over the max allowed.")
print ("You're longest word was, \"" + longestWord + "\"")
print ("There are " + str(val) + " words over 7 characters.")
print ("They were:")
print (wordsOver)
print ("You may want to consider changing them for shorter words.")
else:
print ("That's short enough!")
答案 1 :(得分:0)
i
是否是使用.isalpha()
的字母表中的字符,当遇到空格时它将返回false,因为它是不是字母。
请参阅:https://docs.python.org/2/library/stdtypes.html#str.isalpha
答案 2 :(得分:-1)
isalpha()不会为空格返回true。
此外,还有一系列更好的方法可以做到这一点。您应该查看集合中的Counter类。这是一本字典,可以为您提供所需的信息。