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

回答編集履歴

5

バイトモードで書き出し

2021/03/31 08:28

投稿

退会済みユーザー
answer CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  if response.status_code==200:
17
17
  messages = response.json()
18
- with open('chat.log','a') as f:
18
+ with open('chat.log','ab') as f:
19
19
  for message in messages:
20
20
  body = message['body']
21
21
  for info in info_pattern.findall(body):

4

文字列を結合してからエンコーディング

2021/03/31 08:28

投稿

退会済みユーザー
answer CHANGED
@@ -19,5 +19,5 @@
19
19
  for message in messages:
20
20
  body = message['body']
21
21
  for info in info_pattern.findall(body):
22
- f.write(info.encode('cp932') + '\n')
22
+ f.write((info + '\n').encode('cp932'))
23
23
  ```

3

UTF8->CP932変更

2021/03/30 07:48

投稿

退会済みユーザー
answer CHANGED
@@ -19,5 +19,5 @@
19
19
  for message in messages:
20
20
  body = message['body']
21
21
  for info in info_pattern.findall(body):
22
- f.write(info.encode('utf-8') + '\n')
22
+ f.write(info.encode('cp932') + '\n')
23
23
  ```

2

エンコードの問題に対応(したつもり)

2021/03/30 06:02

投稿

退会済みユーザー
answer CHANGED
@@ -19,5 +19,5 @@
19
19
  for message in messages:
20
20
  body = message['body']
21
21
  for info in info_pattern.findall(body):
22
- f.write(info + '\n')
22
+ f.write(info.encode('utf-8') + '\n')
23
23
  ```

1

改行が入っている場合の対応

2021/03/30 06:01

投稿

退会済みユーザー
answer CHANGED
@@ -1,4 +1,4 @@
1
- こんな感じでいかがでしょうか。
1
+ こんな感じでいかがでしょうか。[info]から[/info]の間に改行が入っている場合でも動きます。
2
2
 
3
3
  ```python3
4
4
  import requests
@@ -6,16 +6,18 @@
6
6
  import re
7
7
 
8
8
  headers = {
9
- 'X-ChatWorkToken': '*********',
9
+ 'X-ChatWorkToken': '*********'
10
10
  }
11
11
 
12
+ info_pattern = re.compile(r'[info](.*?)[/info]', flags=re.DOTALL)
13
+
12
14
  response = requests.get('https://api.chatwork.com/v2/rooms/213313301/messages?force=1', headers=headers)
13
15
 
14
16
  if response.status_code==200:
15
17
  messages = response.json()
16
18
  with open('chat.log','a') as f:
17
- for message in messages:
19
+ for message in messages:
18
20
  body = message['body']
19
- for info in re.findall(r"[info](.*?)[/info]", body):
21
+ for info in info_pattern.findall(body):
20
- f.write(info + '\n')
22
+ f.write(info + '\n')
21
23
  ```