我有两个文件,我需要删除低于某个令牌比率的行,例如
文件 1:
This is a foo bar question
that is not a parallel sentence because it's too long
hello world
文件 2:
c'est le foo bar question
creme bulee
bonjour tout le monde
并且计算的比率是总no. of words in file 1 / total no. of words in file 2
的,如果它低于这个比率,则删除句子。
然后输出是一个联合文件,其中文件 1 和文件 2 中的句子用制表符分隔:
[出去]:
This is a foo bar question\tc'est le foo bar question
hello world\tbonjour tout le monde
这些文件始终具有相同的行数。我一直在这样做,但是如何在 unix bash 而不是使用 python 中做同样的事情?
# Calculate the ratio.
with io.open('file1', , 'r', encoding='utf8') as f1, io.open('file2', , 'r', encoding='utf8') as f2:
ratio = len(f1.read().split()) / float(len(f2.read().split()))
# Check and output to file.
with io.open('file1', , 'r', encoding='utf8') as f1, io.open('file2', , 'r', encoding='utf8') as f2, io.open('fileout', , 'w', encoding='utf8') as fout:
for l1, l2 in zip(file1, file2):
if len(l1.split())/float(len(l2.split())) > ratio:
print>>fout, "\t".join([l1.strip() / l2.strip()])
另外,如果比率计算是基于字符而不是单词,我可以在 python 中做到这一点,但我如何在 unix bash 中实现相同的效果?请注意,差异仅与len(str.split())
和一起计算len(str)
。
# Calculate the ratio.
with io.open('file1', , 'r', encoding='utf8') as f1, io.open('file2', , 'r', encoding='utf8') as f2:
ratio = len(f1.read()) / float(len(f2.read()))
# Check and output to file.
with io.open('file1', , 'r', encoding='utf8') as f1, io.open('file2', , 'r', encoding='utf8') as f2, io.open('fileout', , 'w', encoding='utf8') as fout:
for l1, l2 in zip(file1, file2):
if len(l1)/float(len(l2)) > ratio:
print>>fout, "\t".join([l1.strip() / l2.strip()])