質問するログイン新規登録

回答編集履歴

3

質問変更内容に合わせて変更

2020/01/03 09:48

投稿

shiracamus
shiracamus

スコア5406

answer CHANGED
@@ -1,9 +1,14 @@
1
+ ```python
2
+ def find(lines, target, n=4):
3
+ i = 0
1
- いろいろな方法があると思いますが簡単な例。
4
+ while i < len(lines):
2
- 12333\n444\n があったとしても一致してしまうので、正規表現を使った方がいいでしょうけど。
5
+ if lines[i:i+len(target)] == target:
6
+ i += len(target)
7
+ yield lines[i:i+n]
8
+ i += n
9
+ else:
10
+ i += 1
3
11
 
4
- ```python
5
- >>> open("test.txt").read().split("333\n444\n")[1].splitlines()[:4]
6
- ['555', '666', '777', '888']
12
+ found = list(find(open('test.txt').readlines(), ['333\n', '444\n']))
7
- >>> open("test.txt").read().split("333\n444\n")[1].splitlines()[:-1]
13
+ print(found)
8
- ['555', '666', '777', '888']
9
14
  ```

2

意図しないケースを追記

2020/01/03 09:47

投稿

shiracamus
shiracamus

スコア5406

answer CHANGED
@@ -1,4 +1,5 @@
1
1
  いろいろな方法があると思いますが簡単な例。
2
+ 12333\n444\n があったとしても一致してしまうので、正規表現を使った方がいいでしょうけど。
2
3
 
3
4
  ```python
4
5
  >>> open("test.txt").read().split("333\n444\n")[1].splitlines()[:4]

1

説明文追加

2020/01/03 07:19

投稿

shiracamus
shiracamus

スコア5406

answer CHANGED
@@ -1,3 +1,5 @@
1
+ いろいろな方法があると思いますが簡単な例。
2
+
1
3
  ```python
2
4
  >>> open("test.txt").read().split("333\n444\n")[1].splitlines()[:4]
3
5
  ['555', '666', '777', '888']