【问题标题】:How to split out string occurrences to an individual txt file?如何将出现的字符串拆分为单个 txt 文件?
【发布时间】:2018-05-15 17:04:10
【问题描述】:

例如,我有一个包含这些行的 txt 文件,

chicken
chicken
duck
duck
duck
parrot
parrot
chicken
chicken
chicken

如何逐行阅读并将鸡(2 行)拆分为 1.txt,鸭(3 行)拆分为 2.txt,鹦鹉(2 行)拆分为 3.txt,最后一只鸡(3 行)出现在 4.txt 中?

到这里我才想通,

count = 0

with open("test.txt") as rl:
    for num, line in enumerate (rl, 1):
        s = list(line)
        if "chicken" in line:
            count += 1

            finaljoin = "".join(s)

            print(count)

            with open("chicken.txt", 'a+') as f:
                f.write(finaljoin)

但我上面的解决方案只将整只鸡(总共 5 只)抓到一个文件中。实际的计划是将第一两行抓取到一个 txt 文件,最后两行鸡到另一个 txt 文件。因为它正在被其他动物分裂。

【问题讨论】:

  • 所以显然你只关心里面有“chicken”的行,并且只写入名为“chicken.txt”的文件。这与你的目的完全不同。

标签: python split readline


【解决方案1】:

你可以这样做:

from itertools import groupby

with open('test.txt') as f:
    data = f.read().split('\n')

for ind, (_, g) in enumerate(groupby(data),1):
    with open('{}.txt'.format(ind), 'w') as f:
        f.write('\n'.join(g))

说明:

您可以在此处阅读有关 Itertools groupby 的信息:https://docs.python.org/2/library/itertools.html#itertools.groupby

Groupby 将返回两个元素,键和组。 因此,如果我们想遍历 groupby,我们会这样做:for key, group in groupby(object):for k, g in groupby(object):

现在在这种情况下,键将是 chicken, duck, parrot, chicken,组将是 ['chicken', 'chicken'] , ['duck','duck... ...]

但是(现在是我解释ind, (_, g) 的部分),要在循环时获取索引,我们可以使用 Python 的 enumerate 函数,该函数将返回索引和迭代器。通常它看起来像这样:for index, item in enumerate(list):for ind, i in enumerate(list)

现在假设我们要合并enumerategroupby。然后我们可以这样做:for index, (key, group) in enumerate(groupby(object)): 或更紧凑:for ind, (_, g) ...。在这种情况下,我使用_(这是 Pythonic)来表示我对变量不感兴趣(在这种情况下是键)。

【讨论】:

  • 它有效。无论如何,我不太了解 itertools 的概念。但是“_”和“g”在你的代码中真正做了什么?
  • @IzzatZainol 完成。
  • 感谢@Anton vBR 的清晰解释。我已经标记了答案。
【解决方案2】:

你可以试试:

count = 0
with open("test.txt") as readFile:
    previous_line = ""
    archive_name = ""
    for line in readFile:
        if line != previous_line:
             previous_line = line
             count += 1
             archive_name = str(count)+".txt"
        with open(archive_name, 'a+') as f:  
            f.write(line)

这将在 1.txt 中保存“chicken chicken”,在 2.txt 中保存“duck duck duck”,在 3.txt 中保存“parrot parrot”,在 4.txt 中保存“chicken chicken chicken”

【讨论】:

  • 我已经尝试过您的解决方案。但它在每一行都分裂。
  • 它正在工作。但是你知道为什么它仍然只用“鸡”创建一个额外的最终(不相关的)文件吗?
【解决方案3】:

其实你还没想清楚。您没有分割条款;您所做的就是搜索“chicken”,无论它出现在哪里,然后将这些重组的行转储到“chicken.txt”文件中。你没有为任何其他动物做任何准备,也没有试图在逻辑上找到这些休息点。还有,这里面有很多多余的代码,比如反复打开你的输出文件,生成num,从来没用过。

如果需要,在纸上画出你的基本逻辑。您缺少的关键步骤是检查前一个动物与当前动物。这就像

previous = None
with open("test.txt") as zoo:
    for animal in zoo:
        if animal == previous:
            # Process same animal
        else:
            # Process new animal
        previous = animal   # remember animal for next iteration

你能从那里拿走吗? for num, line in enumerate (rl, 1):

【讨论】:

  • 谢谢。我有一个粗略的想法。无论如何,我为其他目的保留了生成号码:)
猜你喜欢
  • 1970-01-01
  • 2022-09-27
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多