1

我正在使用 WC -l 来计算文本文档中的行数。但是我在这里遇到了问题。

我得到了一个 python 代码,它将不同的数字组合写入不同的文件。每个文件在单独的行中包含每个组合的编号。

当我使用 wc -l 时,它没有计算最后一行!

下面是python代码:

import os
import itertools
lst = [6,7,8,9,12,19,20,21,23,24,26,27,28,29,43,44]
combs = []
for i in xrange(1, len(lst)+1):
els = [list(x) for x in itertools.combinations(lst, i)]
combs.extend(els)
for combination in els:
  combination_as_strings = map(str, combination)
  filename = "_".join(combination_as_strings) + ".txt"
  filename = os.path.join("Features", filename)
  with open(filename, 'w') as output_file:
     output_file.write("\n".join(combination_as_strings))

提前致谢,

艾哈迈德

4

4 回答 4

4

您正在使用的join是在行之间放置换行符,但不是在最后一行的末尾。因此,wc不计算最后一行(它计算换行符的数量)。

output_file.write("\n")在脚本末尾的with子句中添加:

  with open(filename, 'w') as output_file:
     output_file.write("\n".join(combination_as_strings))
     output_file.write("\n")
于 2013-01-30T00:21:19.793 回答
2

我认为您看到的是这种情况的变体:

$ printf '1\n2\n3' | wc -l

在 Bash 提示符下输入 -- 打印2,因为没有 final\n

相比于:

$ printf '1\n2\n3\n' | wc -l

打印 3 因为 final \n

Python 文件方法不会将 a 附加\n到它们的输出中。要修复您的代码,请使用如下 writelines

with open(filename, 'w') as output_file:
    output_file.writelines(["\n".join(combination_as_strings),'\n'])

或打印到文件:

with open(filename, 'w') as output_file:
     print >>output_file, "\n".join(combination_as_strings)

或使用格式模板:

with open(filename, 'w') as output_file:
     output_file.write("%s\n" % '\n'.join(combination_as_strings))
于 2013-01-30T00:22:27.457 回答
1

为什么不使用writelines

output_file.writelines(line+"\n" for line in combination_as_strings)
于 2013-01-30T00:21:50.057 回答
1

该命令计算文件 ( )wc中换行符的数量。\n

因此,如果文件中有 10 行,它将返回 9,因为您将有 9 个换行符。

您可以通过在每个文件的末尾添加一个空的新行来使其工作。

于 2013-01-30T00:21:57.983 回答