Python:读取文本文件中的行并计算正下方行相同的实例
Python: Reading lines in a text file and counting instances where lines directly below are identical
我是 Python 的新手,正在寻求帮助。
我有一个大文本文件,我想搜索并计算一行与上面一行相同的次数。这是我目前所拥有的。
f = open('test.txt')
counter = 0
for line in f:
nextline = f.next()
if line == nextline:
counter = counter + 1
print counter
f.close()
这会分组并比较第一行和第二行,然后是第三行和第四行,依此类推。我怎样才能调整程序来比较第一行和第二行,然后是第二行和第三行,第三行和第四行等等。
任何帮助,将不胜感激。
谢谢
通过调用 f.next()
,您已经进入下一行。但是,您可以使用存储上一行的变量 old_line
。每次在循环结束时,您设置 old_line
以引用 line
。此外,您最初将 old_line
设置为 None
以确保不计算第一行。
counter = 0
with open('test.txt') as f:
old_line = None
for line in f:
if line == old_line:
counter += 1
old_line = line
print counter
像这样保留上一行的引用:
f = open('test.txt')
counter = 0
prevLine = None
for line in f:
if line == prevLine:
counter = counter + 1
prevLine = line
print counter
f.close()
我认为应该有一个奇怪的解决方案......给你
from functools import reduce #if you are useing Python 3+
count = 0
def compare_string(prev, new):
global count
if prev == new:
count += 1
return new
with open('test.txt') as f:
reduce(compare_sring, f)
你可以试试这个:
f = open('filename.txt').read().splitlines()
print len([f[i] for i in range(len(f)-1) if f[i] == f[i+1]])
我是 Python 的新手,正在寻求帮助。 我有一个大文本文件,我想搜索并计算一行与上面一行相同的次数。这是我目前所拥有的。
f = open('test.txt')
counter = 0
for line in f:
nextline = f.next()
if line == nextline:
counter = counter + 1
print counter
f.close()
这会分组并比较第一行和第二行,然后是第三行和第四行,依此类推。我怎样才能调整程序来比较第一行和第二行,然后是第二行和第三行,第三行和第四行等等。 任何帮助,将不胜感激。 谢谢
通过调用 f.next()
,您已经进入下一行。但是,您可以使用存储上一行的变量 old_line
。每次在循环结束时,您设置 old_line
以引用 line
。此外,您最初将 old_line
设置为 None
以确保不计算第一行。
counter = 0
with open('test.txt') as f:
old_line = None
for line in f:
if line == old_line:
counter += 1
old_line = line
print counter
像这样保留上一行的引用:
f = open('test.txt')
counter = 0
prevLine = None
for line in f:
if line == prevLine:
counter = counter + 1
prevLine = line
print counter
f.close()
我认为应该有一个奇怪的解决方案......给你
from functools import reduce #if you are useing Python 3+
count = 0
def compare_string(prev, new):
global count
if prev == new:
count += 1
return new
with open('test.txt') as f:
reduce(compare_sring, f)
你可以试试这个:
f = open('filename.txt').read().splitlines()
print len([f[i] for i in range(len(f)-1) if f[i] == f[i+1]])