【问题标题】:Count consecutive occurrences of values in a .txt file计算 .txt 文件中值的连续出现次数
【发布时间】:2016-04-13 14:21:05
【问题描述】:

我有一个 .txt 文件,其中有两个单词在不同的行中重复。

这是一个例子。 (实际大概有八万行)

ANS
ANS
ANS
AUT
AUT
AUT
AUT
ANS
ANS
ANS
ANS
ANS

我正在尝试开发一些 Python 代码来计算连续行并返回它们重复的次数。所以对于这个例子,我想将 [3,4,5] 返回到另一个 .txt 文件

word="100011010"
count=1
length=""

for i in range(1, len(word)):

    if word[i-1] == word[i]:
       count += 1

    else:
        length += word[i-1]+" repeats "+str(count)+", "
        count=1

length += ("and "+word[i]+" repeats "+str(count))
print (length)

这个概念类似于上面的字符串代码。有没有办法通过列表来做到这一点?

【问题讨论】:

  • 您可以使用完全相同的代码。只需将word 更改为your_list :)
  • 抱歉,我最后一个问题的措辞有误。现在信息在一个 .txt 文件中,我是否必须将其转换为列表?
  • 有没有办法直接从 .txt 文件中读取?是否可以从中挑出某一行(如word[2])。有没有办法说 line[2]?
  • @slyness 不确定您的应用程序是什么,但您也可能会发现这适用:stackoverflow.com/questions/24342047/…

标签: python text


【解决方案1】:

您可以这样读取整个文件:

content = []
with open('/path/to/file.txt', 'r') as file
    content = file.readlines()
    #Maybe you want to strip the lines
    #content = [line.strip() for line in file.readlines()]

这里有一个包含文件所有行的列表

def count_consecutive_lines(lines):
    counter = 1
    output = ''
    for index in range(1, len(lines)):
        if lines[index] != lines[index-1]:
            output += '{} repeats {} times.\n'.format(lines[index], counter)
            counter = 1
        counter += 1
   return output

然后这样称呼

print(count_consecutive_lines(content))

【讨论】:

  • 谢谢,我会试试这个。我可以执行 file.write('\n'.join) 将计数写入另一个 .txt 文件(\n 为每个新行)吗?
  • @slynes 是的,你可以
【解决方案2】:

不将整个文件加载到内存中的答案:

last = None
count = 0
result = []

with open('sample.txt', 'rb') as f:
    for line in f:
        line = line.strip()
        if line == last:
            count = count + 1
        else:
            if count > 0:
                result.append(count)
            count = 1
            last = line

    result.append(count)
    print result

结果:

[3, 4, 5]

更新

列表包含整数,你只能join字符串,所以你必须转换它。

outFile.write('\n'.join(str(n) for n in result))

【讨论】:

  • 谢谢,效果很好。我试图使用 outFile.write('\n'.join(result)) (outFile 已定义)将结果写入 .txt 文件,而不是最后打印,但由于某种原因它不起作用
  • @slynes 更新了答案。
【解决方案3】:

您可以尝试将文件数据转换为列表,并按照下面给出的方法:

with open("./sample.txt", 'r') as fl:
    fl_list = list(fl)
    unique_data = set(fl_list)
    for unique in unique_data:
        print "%s - count: %s" %(unique, fl_list.count(unique))

#output:
ANS - count: 8
AUT - count: 4

【讨论】:

  • 他不想要一个单词的总计数,而是一个单词的连续计数,看看他的例子 ans 出现在期望的最终结果中,两次。
  • 不是 OP 想要的......计算连续的相似项目......不计算所有相似项目
  • 那很好。但我可以单独计算吗?比如ANS- count: 3, AUT - count: 4, ANS - count: 5。我需要记录AUT分别出现了多少次。
【解决方案4】:

打开你的文件并阅读它来计数:

l=[]
last=''
with open('data.txt', 'r') as f:
    data = f.readlines()

    for line in data:
        words = line.split()
        if words[0]==last:
            l[-1]=l[-1]+1
            last=words[0]
        else:
            l.append(1)
        if last=='':
            last=words[0]

【讨论】:

  • 如果条件在语法上不正确,赋值与比较。
【解决方案5】:

这是您的预期输出:)

with open("./sample.txt", 'r') as fl:
    word = list(fl)
    count=1
    length=[]
    for i in range(1, len(word)):
        if word[i-1] == word[i]:
           count += 1
        else:
            length.append(count)
            count=1
    length.append(count)
    print (length)

#output as you excpect:
[3, 4, 5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多