Python-一个for循环,在to_analyze

时间:2018-11-13 02:40:49

标签: python python-2.7

需要帮助!

Python的新手,已经被困了好几天(因此,为什么我要在这里发布,不得已!)

我需要找到最大,最小(基于单词数的最长和最短行)和每行的平均单词数(用于to_analyze字符串)

我的问题是,我只能获得每行的单词数,但它不准确,因为它仅打印每行的单词数,而不是哪一行具有最大单词数和最小单词数。

这是我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Task 03"""

import re
from decimal import *

def lexicographics(to_analyze):
"""


"""
lines=0
num_of_words=0
max_words=0
min_words=0
mostWordsInLine=0

for line in to_analyze.split('\n'):
    lines +=1
    words=line.split()
    if len(words) > mostWordsInLine and len(words) != None:
        mostWordsInLine = len(words)
        num_of_words=len(words)
        max_words=max_words+len(words)
        print num_of_words
print "Decimal({:.1f})".format(Decimal(max_words) / Decimal(lines))

当前输出:

>>> import task_03
>>> task_03.lexicographics('''Don't stop believing,
Hold on to that feeling.''')
3
5
Decimal(4.0)

您可以看到^-我得到了正确的单词数,但是它计算的是每一行的单词数,而不是我所需要的。

输出应为:

>>> import task_03
>>> task_03.lexicographics('''Don't stop believing,
Hold on to that feeling.''')
(5, 3, Decimal(4.0))

如果我想让它也测量另一个文件中的行

>>> import task_03
>>> import data
>>> task_03.lexicographics(data.SHAKESPEARE)
(12, 5, Decimal('8.14'))

任何帮助/提示都将不胜感激!

1 个答案:

答案 0 :(得分:1)

告诉您,这可以全部用一个简单的$result1 = mysqli_query($DBconn,"SELECT DISTINCT sensor_code FROM bldgSensors"); echo "<table border='1'> <tr> <th>Distinct sensor codes</th> <th>Count</th> </tr>"; while($row1 = mysqli_fetch_array($result1)) { echo "<tr>"; echo "<td>" . $row1['sensor_code'] ."</td>"; } echo "</table>"; mysqli_close($DBconn);

def

然后:

from decimal import Decimal
def f(s):
    lines=list(map(lambda x: len(x.split()),s.splitlines()))
    return (max(lines),min(lines),Decimal(sum(lines))/Decimal(len(lines)))

是:

print(f("Don't stop believing,\nHold on to that feeling."))