简体   繁体   English

获取文本文件中的特定行并将其传递给数组

[英]Getting specific lines in a text file and pass it to an array

Not sure if this has been asked. 不确定是否有人问过这个问题。 But here it goes. 但在这里它。

Let's say I have a text file containing 假设我有一个包含的文本文件

1 Why
2 We
3 Please
4 OR
5 I
6 AM
7 HUMAN
8 OR
9 MY
10 time
11 to
12 eat

Now I want to get lines 5-7 and 9-12 then put it in an array. 现在我想得到5-7和9-12行然后把它放在一个数组中。 Do note that the OR word acts like a delimiter in the text file. 请注意,OR字在文本文件中的作用类似于分隔符。

I know the usual way of reading a text file in python is using a for loop, but I cant think of a way to do this by using a for loop or any other methods. 我知道在python中读取文本文件的常用方法是使用for循环,但我不能想办法通过使用for循环或任何其他方法来实现这一点。

You can do 你可以做

data = open(<textfile>).read()
segments = data.split('OR')

and then split the segments by \\n to get lines in that segment 然后用\\n分割段以获取该段中的行

lines = [seg.split("\n") for seg in segments]
import csv;  
import re;  
crs = csv.reader(open("D:/a.txt", "r"));  
line = ""  
for each in crs:  
    line = line + each[0];  

print re.split('OR',line)  

Answer: 回答:

['WhyWePlease', 'IAMHUMAN', 'ME'] ['WhyWePlease','IAMHUMAN','我']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM