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

回答編集履歴

1

文字化け対策

2017/04/19 04:35

投稿

8524ba23
8524ba23

スコア38350

answer CHANGED
@@ -4,16 +4,18 @@
4
4
  import lxml.html
5
5
  import pandas as pd
6
6
 
7
- df = pd.DataFrame({'column1':[1,2], 'column2':[3,4]}, index = ['index1','index2'])
7
+ df = pd.DataFrame({'列1':[1,2], '列2':[3,4]}, index = ['index1','index2']) # 日本語を含む
8
8
  df2 = df.to_html()
9
+
9
10
  table = lxml.html.fromstring(df2)
10
11
 
11
12
  # rootにdivを配置し、配下にtableとp(コメント)を配置
13
+ # 文字化けしないようにfromstringではunicode文字列で渡し、tostringではエンコーディングを指定する
12
- root = lxml.html.fromstring("<div></div>")
14
+ root = lxml.html.fromstring(u'<div></div>')
13
15
  root.append( table)
14
- comment = lxml.html.fromstring('<p>comment</p>')
16
+ comment = lxml.html.fromstring(u'<p>コメント</p>')
15
17
  root.append(comment)
16
- html = lxml.html.tostring(root)
18
+ html = lxml.html.tostring(root,encoding='utf-8')
17
19
  print(html)
18
20
  ```
19
21
  結果
@@ -22,8 +24,8 @@
22
24
  <thead>
23
25
  <tr style="text-align: right;">
24
26
  <th></th>
25
- <th>column1</th>
27
+ <th>列1</th>
26
- <th>column2</th>
28
+ <th>列2</th>
27
29
  </tr>
28
30
  </thead>
29
31
  <tbody>
@@ -38,7 +40,7 @@
38
40
  <td>4</td>
39
41
  </tr>
40
42
  </tbody>
41
- </table><p>comment</p></div>
43
+ </table><p>コメント</p></div>
42
44
  ```
43
45
  詳細は以下などが参考になります。
44
46
  [lxmlでhtmlを処理する](http://www.cafe-gentle.jp/challenge/tips/python_tips_001.html#2)