【问题标题】:Get newline stats for a text file in Python在 Python 中获取文本文件的换行统计信息
【发布时间】:2015-04-17 09:49:17
【问题描述】:

我在 git 文件中有一个讨厌的 CRLF / LF 冲突,可能是从 Windows 机器提交的。是否有跨平台的方式(最好在 Python 中)通过文件检测哪种类型的换行符占主导地位?

我有这个代码(基于https://stackoverflow.com/a/10562258/239247 的想法):

import sys
if not sys.argv[1:]:
  sys.exit('usage: %s <filename>' % sys.argv[0])

with open(sys.argv[1],"rb") as f:
  d = f.read()
  crlf, lfcr = d.count('\r\n'), d.count('\n\r')
  cr, lf = d.count('\r'), d.count('\n')
  print('crlf: %s' % crlf)
  print('lfcr: %s' % lfcr)
  print('cr: %s' % cr)
  print('lf: %s' % lf)
  print('\ncr-crlf-lfcr: %s' % (cr - crlf - lfcr))
  print('lf-crlf-lfcr: %s' % (lf - crlf - lfcr))
  print('\ntotal (lf+cr-2*crlf-2*lfcr): %s\n' % (lf + cr - 2*crlf - 2*lfcr))

但它给出了错误的统计数据(this file):

crlf: 1123
lfcr: 58
cr: 1123
lf: 1123

cr-crlf-lfcr: -58
lf-crlf-lfcr: -58

total (lf+cr-2*crlf-2*lfcr): -116

【问题讨论】:

  • 像 sorrat 一样,我为该文件获得了 1123 个 crlf 对,其他 3 个 EOL 标记为 0。
  • @PM2Ring 我需要一个更好的测试文件。我认为这个实际上包含混合换行符。

标签: python newline


【解决方案1】:
import sys


def calculate_line_endings(path):
    # order matters!
    endings = [
        b'\r\n',
        b'\n\r',
        b'\n',
        b'\r',
    ]
    counts = dict.fromkeys(endings, 0)

    with open(path, 'rb') as fp:
        for line in fp:
            for x in endings:
                if line.endswith(x):
                    counts[x] += 1
                    break
    print(counts)


if __name__ == '__main__':
    if len(sys.argv) == 2:
        calculate_line_endings(sys.argv[1])

    sys.exit('usage: %s <filepath>' % sys.argv[0])

为您的文件提供输出

crlf: 1123
lfcr: 0
cr: 0
lf: 0

够了吗?

【讨论】:

  • 这个不错。你知道line in open(filename, "rb"): 是如何正确检测线条的吗?只是为了了解极端情况。
  • 对不起,我不知道。可能是PEP-278中的原因@
【解决方案2】:

发布的代码无法正常工作,因为 Counter 正在对文件中的字符进行计数 - 它不会寻找像 \r\n\n\r 这样的字符对。

这里有一些 Python 2.6 代码,它使用正则表达式查找 4 个 EOL 标记 \r\n\n\r\r\n 的每次出现。诀窍是在查找单个字符 EOL 标记之前查找 \r\n\n\r 对。

出于测试目的,它会创建一些随机文本数据;我在注意到您指向测试文件的链接之前写了这篇文章。

#!/usr/bin/env python

''' Find and count various line ending character combinations

    From http://stackoverflow.com/q/29695861/4014959

    Written by PM 2Ring 2015.04.17
'''

import random
import re
from itertools import groupby

random.seed(42)

#Make a random text string containing various EOL combinations
tokens = list(2*'ABCDEFGHIJK ' + '\r\n') + ['\r\n', '\n\r']
datasize = 300
data = ''.join([random.choice(tokens) for _ in range(datasize)])
print repr(data), '\n'

#regex to find various EOL combinations
pat = re.compile(r'\r\n|\n\r|\r|\n')

eols = pat.findall(data)
print eols, '\n'

grouped = [(len(list(group)), key) for key, group in groupby(sorted(eols))]
print sorted(grouped, reverse=True)

输出

'FAHGIG\rC AGCAFGDGEKAKHJE\r\nJCC EKID\n\rKD F\rEHBGICGCHFKKFH\r\nGFEIEK\n\rFDH JGAIHF\r\n\rIG \nAHGDHE\n G\n\rCCBDFK BK\n\rC\n\r\rAIHDHFDAA\r\n\rHCF\n\rIFFEJDJCAJA\r\n\r IB\r\r\nCBBJJDBDH\r FDIFI\n\rGACDGJEGGBFG\n\rBGGFD\r\nDBJKFCA BIG\n\rC J\rGFA HG\nA\rDB\n\r \n\r\n EBF BK\n\rHJA \r\n\n\rDIEI\n\rEDIBEC E\r\nCFEGGD\rGEF EC\r\nFIG GIIJCA\n\r\n\rCFH\r\n\r\rKE HF\n\rGAKIG\r\nDDCDHEIFFHB\n C HAJFHID AC\r' 

['\r', '\r\n', '\n\r', '\r', '\r\n', '\n\r', '\r\n', '\r', '\n', '\n', '\n\r', '\n\r', '\n\r', '\r', '\r\n', '\r', '\n\r', '\r\n', '\r', '\r', '\r\n', '\r', '\n\r', '\n\r', '\r\n', '\n\r', '\r', '\n', '\r', '\n\r', '\n\r', '\n', '\n\r', '\r\n', '\n\r', '\n\r', '\r\n', '\r', '\r\n', '\n\r', '\n\r', '\r\n', '\r', '\r', '\n\r', '\r\n', '\n', '\r'] 

[(17, '\n\r'), (14, '\r'), (12, '\r\n'), (5, '\n')]

这是一个从命名文件中读取数据的版本,遵循问题中的代码模式。

import re
from itertools import groupby
import sys

if not sys.argv[1:]:
    exit('usage: %s <filename>' % sys.argv[0])

with open(sys.argv[1], 'rb') as f:
    data = f.read()

print repr(data), '\n'

#regex to find various EOL combinations
pat = re.compile(r'\r\n|\n\r|\r|\n')

eols = pat.findall(data)
print eols, '\n'

grouped = [(len(list(group)), key) for key, group in groupby(sorted(eols))]
print sorted(grouped, reverse=True)

【讨论】:

  • 不错的方法。特别酷的是它有测试数据可供比较。
【解决方案3】:

在 git 中处理行尾的最好方法是使用 git 配置。您可以定义对全局、特定存储库或特定文件的行尾必须执行的操作。在.gitattributes 文件中,您可以定义某些文件必须在每次检出时转换为系统的本机行尾,并在检入时转换回。详细说明见GitHub line endings help

【讨论】:

  • 我不想转换任何东西,git可以让我的文件默认保持原样吗?
【解决方案4】:

据我所见,我建议检查您是否有以下情况: \r\n\r\n\r\n。按照您的代码,这将计算以下内容:

crlf: 3 -- [\r\n][\r\n][\r\n]
lfcr: 2 -- \r[\n\r][\n\r]\n
cr: 3   -- [\r]\n[\r]\n[\r]\n
lf: 3   -- \r[\n]\r[\n]\r[\n]

cr-crlf-lfcr: -2
lf-crlf-lfcr: -2

total (lf+cr-2*crlf-2*lfcr): -4

如您所见,一些\n 和一些\rcrlflfcr 计算了两次。相反,您可以逐行阅读并计算行尾line.endswith()。要获得 crlf 的准确统计信息,您可以将 \r\n\n\r 计为 cr+1 和 lf+1。

【讨论】:

    猜你喜欢
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    相关资源
    最近更新 更多