【问题标题】:Count number of times a substring occures within split txt file计算子字符串在拆分文本文件中出现的次数
【发布时间】:2014-07-12 22:54:51
【问题描述】:

我有一个名为 test1.txt 的 .txt 文件,其中包含:

apple
P apple apple
P apple
Pbanana apple P apple apple apple

我使用此代码根据字母 P 将其分成类别:

import re

Apple_split = open("test1.txt").read().split("P")

print(Apple_split_split)

我现在想计算单词 apple 在每个拆分中出现的次数。希望能输出 1、2、1、1、3 或类似的输出。任何帮助将不胜感激。

【问题讨论】:

标签: python


【解决方案1】:

在列表推导中使用string.count 将其应用于每个拆分段。

with open('test1.txt') as text_file:
    print [segment.count('apple') for segment in text_file.read().split("P")]

【讨论】:

  • 我试过这个,但它只是给了我苹果的总数。我试图找出每个拆分中的苹果数量。
  • 列表理解完全符合您的要求。试试这里写的;它返回 [1, 2, 1, 1, 3]。 repl.it/VSm
【解决方案2】:

你可以这样做:

f = open('test1.txt').read().split('P')
apple_counts = [segment.count('apple') for segment in f]
print apple_counts #[1, 2, 1, 1, 3]

上面使用'P'分割每个段后使用简单的列表推导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多