【问题标题】:Python adding up the length of lists of numberPython将数字列表的长度相加
【发布时间】:2016-05-18 04:38:43
【问题描述】:

所以我试图在 txt 文件中找到一个特定的单词,并将它的出现加起来,我使用的代码

import re

pattern = re.compile(r"\bshall\b")
pattern1 = re.compile(r"\bmay not\b")
pattern2 = re.compile(r"\bmust\b")

with open('C:\Python27\projects\Alabama\New folder\\4.txt', 'r') as myfile:
 for line in myfile:
    m = re.findall(pattern, line)
    #m1 = re.findall(pattern1, line)
    #m2 =  re.findall(pattern2,line)

    k = len(m)
    #k1 = len(m1)
    #k2 = len(m2)
    #sumk = sum(len(k) for k in myfile)
    print k

当我打印出 k 时,它会给出 [0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 3, 0, 2 ...... ...] 我可以说这些是文本每一行中字符串“shall”的出现次数,我的问题是如何将这些数字列表相加以获得“shall”的总和/总出现次数文本文件。

【问题讨论】:

  • k = len(m)+k ,在外面定义k。

标签: python list python-2.7 sum frequency


【解决方案1】:

一种方法是使用累计:

total = 0
for line in myfile:
    m = re.findall(pattern, line)
    total += len(m)

print total

【讨论】:

    【解决方案2】:

    如果您打算sum 一个列表,您可以使用sum,但您需要在外部定义k,这样它就不会每次都被替换新值:

    k = [] #define k as empty list here
    for line in myfile:
        m = re.findall(pattern, line)
        k.append(len(m)) #append the list with new item
    val = sum(k) #get the sum here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2022-12-17
      相关资源
      最近更新 更多