wc -l 和 python 行数不同
wc -l and python line count differ
我想知道为什么使用 bash 的简单行计数给我的行数与使用 python(版本 3.6)计算给定 here (train_en.txt
) and here 的文件的行数不同(train_de.txt
)。在 bash 中,我正在使用命令:
wc -l train_en.txt
wc -l train_de.txt
输出分别是4520620和4520620。
在 python 中,我正在使用命令:
print(sum(1 for line in open('train_en.txt')))
print(sum(1 for line in open('train_de.txt')))
输出分别是4521327和4521186。
当我使用 python 命令时
len(open('train_en.txt').read().splitlines())
len(open('train_de.txt').read().splitlines())
我分别得到 4521334 和 4521186(train_en.txt
结果与之前的 python 命令的结果不匹配)。
供参考,这些是通过连接 Common Crawl, Europarl, and News Commentary datasets (in that order) from the WMT '14 English to German translation task 生成的平行文本语料库,行数应该相同。
\n
s 可以被视为 multi-byte 个字符,而不是实际的 \n
。可以通过使用字节串编码来避免这种情况。命令
print(sum(1 for line in open('train_en.txt', mode='rb')))
print(sum(1 for line in open('train_de.txt', mode='rb')))
len(open('train_en.txt', mode='rb').read().splitlines())
len(open('train_de.txt', mode='rb').read().splitlines())
全部结果为4520620(匹配wc -l
的输出),这意味着英语和德语语料库是按要求平行的。
感谢@CharlesDuffy 的帮助。
我想知道为什么使用 bash 的简单行计数给我的行数与使用 python(版本 3.6)计算给定 here (train_en.txt
) and here 的文件的行数不同(train_de.txt
)。在 bash 中,我正在使用命令:
wc -l train_en.txt
wc -l train_de.txt
输出分别是4520620和4520620。
在 python 中,我正在使用命令:
print(sum(1 for line in open('train_en.txt')))
print(sum(1 for line in open('train_de.txt')))
输出分别是4521327和4521186。
当我使用 python 命令时
len(open('train_en.txt').read().splitlines())
len(open('train_de.txt').read().splitlines())
我分别得到 4521334 和 4521186(train_en.txt
结果与之前的 python 命令的结果不匹配)。
供参考,这些是通过连接 Common Crawl, Europarl, and News Commentary datasets (in that order) from the WMT '14 English to German translation task 生成的平行文本语料库,行数应该相同。
\n
s 可以被视为 multi-byte 个字符,而不是实际的 \n
。可以通过使用字节串编码来避免这种情况。命令
print(sum(1 for line in open('train_en.txt', mode='rb')))
print(sum(1 for line in open('train_de.txt', mode='rb')))
len(open('train_en.txt', mode='rb').read().splitlines())
len(open('train_de.txt', mode='rb').read().splitlines())
全部结果为4520620(匹配wc -l
的输出),这意味着英语和德语语料库是按要求平行的。
感谢@CharlesDuffy 的帮助。