2017-08-11 33 views
0

中国語のテキストを抽出してファイルに書き込む際に問題があります。中国語のテキストをPythonでファイルに書き込む方法

str = "全球紧张致富豪财富缩水 贝索斯丁磊分列跌幅前两位"; 
f=open('test.txt','w'); 
f.write(str); 

上記のコードは正常に動作します。ちょっとしたことを示す下のコードでファイルに書き込んでいます。

import requests; 
from bs4 import BeautifulSoup 

f=open('data.txt','w'); 

def techSinaCrawler(): 
    url="http://tech.sina.com.cn/" 
    source_code = requests.get(url) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text, "html.parser") 
    for li in soup.findAll('li',{'data-sudaclick': 'yaowenlist-1'}): 
     for link in li.findAll('a'): 
      href = link.get('href') 
      techSinaInsideLinkCrawler(href);    

def techSinaInsideLinkCrawler(url): 

    source_code = requests.get(url) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text, "html.parser") 
    for data in soup.findAll('h1',{'id': 'main_title'}): 
     str='main_title'+':'+ data.string 
     f.write(str); 
     f.write('\n'); 

techSinaCrawler(); 

のPython 2では、ヘルプ

+0

使用している文字セットは何ですか? – Jay

+0

ウェブサイトでUTF-8文字セットを使用 –

+0

[This](https://stackoverflow.com/questions/20205455/how-to-correctly-parse-utf-8-encoded-html-to-unicode-strings-with- beautifulsoup)と[This(https://stackoverflow.com/questions/7219361/python-and-beautifulsoup-encoding-issues)は、BeautifulSoupのエンコーディングの問題を扱うのに役立つかもしれません。 – Ramon

答えて

0

は...

ただ中国語のテキストとして出力を得るために

plain_text = source_code.text to plain_text = source_code.content 

を.contentするの.textを変更しました。

希望の結果を得ました

0

ためのおかげで、それはあなたがASCII以外のエンコーディングを扱っている場合)(codecs.open使用することをお勧めします。そうすれば、手作業でエンコードする必要はありません。あなたはファイル名に非ASCII文字を期待している場合にも、os.walk()はUnicode文字列を渡す必要があります:

import codecs 
with codecs.open("c:/Users/me/filename.txt", "a", encoding="utf-8") as d: 
    for dir, subdirs, files in os.walk(u"c:/temp"): 
     for f in files: 
     fname = os.path.join(dir, f) 
     print fname 
     d.write(fname + "\n") 

(d.close呼び出すする必要はありません)、とのブロックはすでにの世話をしますそれ。解決

関連する問題