【问题标题】:How to extract subset of data in groups before and after a string如何在字符串之前和之后提取组中的数据子集
【发布时间】:2019-09-24 17:20:25
【问题描述】:

我有一个文本文件。在基于特定单词的文本文件中,它应该将数据分为两组,例如特定单词之前的所有内容为一组,特定单词之后的所有内容为另一组

类似这样的文本文件

hello every one 
Is any space here?

CHAIN

every thing of the 

file lies here

基于 CHAIN 我们将文本文件分成两组

group 1
hello every one 
Is any space here?
group 2
every thing of the 

file lies here

【问题讨论】:

  • 你的意思是使用split?
  • 您可以通过关键字拆分字符串,只需将文件加载到某个变量,例如contents,然后使用您的关键字调用拆分方法,例如contents.split("CHAIN")

标签: python python-3.x text-processing


【解决方案1】:

您可以尝试使用拆分的解决方案,并使用下面给出的索引访问每个字符串。

a = """
hello every one 
Is any space here?

CHAIN

every thing of the 

file lies here
"""

print(a.split("CHAIN")[0])
print(a.split("CHAIN")[1])

【讨论】:

    【解决方案2】:

    你提到你有一个文本文件说test.txt

    你的代码:

    with open("test.txt", "r") as f:
        data = f.readlines()
    
    part1, part2 = ("".join(data).split("CHAIN"))
    print(part1)
    print(part2)
    

    给我:

    hello every one
    Is any space here?
    
    
    
    
    every thing of the
    
    file lies here
    

    否则其他解决方案也不错。

    【讨论】:

      【解决方案3】:

      只是为了完整性(其他答案也可以):

      如果你有一个文本文件

      file = open('file.txt', 'r').read()
      
      print(file.split('CHAIN'))
      
      # if you want to remove the new spaces (\n)
      
      print([text.strip() for text in file.split('CHAIN')])
      

      【讨论】:

        猜你喜欢
        • 2015-06-06
        • 2012-02-10
        • 2019-10-13
        • 2014-11-24
        • 2018-06-27
        • 1970-01-01
        • 2020-04-18
        • 1970-01-01
        • 2020-02-14
        相关资源
        最近更新 更多