以下方法将读取您的文件,并为您提供非边界线列表:
from itertools import groupby
with open('input.txt') as f_input:
for k, g in groupby(f_input, lambda x: not x.startswith('-BORDER-')):
if k:
print([line.strip() for line in g])
所以如果你的输入文件是:
-BORDER-
text
-BORDER-
text
-BORDER-
this is some text
with words
on different lines
-BORDER-
它将显示以下输出:
['text']
['text']
['this is some text', 'with words', 'on different lines']
这可以通过逐行读取文件,并使用 Python 的 groupby 函数对与给定测试匹配的行进行分组来实现。在这种情况下,测试是行是否以-BORDER- 开头。它返回以下所有返回相同结果的行。 k 是测试结果,g 是匹配行组。所以如果测试结果是True,说明它不是以-BORDER-开头的。
接下来,由于您的每一行都有一个换行符,因此使用列表推导从每个返回的行中删除它。
如果您想计算单词(假设它们由空格分隔),那么您可以执行以下操作:
from itertools import groupby
with open('input.txt') as f_input:
for k, g in groupby(f_input, lambda x: not x.startswith('-BORDER-')):
if k:
lines = list(g)
word_count = sum(len(line.split()) for line in lines)
print("{} words in {}".format(word_count, lines))
给你:
1 words in ['text\n']
1 words in ['text\n']
9 words in ['this is some text\n', 'with words \n', 'on different lines\n']