[英]How to extract subset of data in groups before and after a string
I have a text file. 我有一个文本文件。 In text file based on specific word it should make the data into two groups like everything before specific word as 1 group and every thing after specific word as another group 在基于特定单词的文本文件中,它应该将数据分成两组,例如特定单词之前的所有单词作为1组,并且将特定单词之后的所有内容作为另一组
text file some thing like this 文本文件有点像这样
hello every one
Is any space here?
CHAIN
every thing of the
file lies here
Based on CHAIN we separate text file into two groups 基于CHAIN,我们将文本文件分成两组
group 1
hello every one
Is any space here?
group 2
every thing of the
file lies here
You mentioned you have a text file say test.txt
. 你提到你有一个文本文件说test.txt
。
You code: 你编码:
with open("test.txt", "r") as f:
data = f.readlines()
part1, part2 = ("".join(data).split("CHAIN"))
print(part1)
print(part2)
Gives me: 给我:
hello every one
Is any space here?
every thing of the
file lies here
Otherwise other solution is also good. 否则其他解决方案也很好。
you can try a solution with split ans access each string using index as given below. 您可以尝试使用split ans访问每个字符串的解决方案,使用索引,如下所示。
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])
just for completeness (other answers work as well): 只是为了完整性(其他答案也有效):
if you have a text file 如果你有一个文本文件
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')])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.