0
我正在嘗試讀取tweets並將這些tweet寫入文件。但是,當我嘗試將某些推文寫入文件時,我收到了UnicodeEncodeErrors。有沒有辦法刪除這些非UTF-8字符,以便我可以寫出推文的其餘部分?從python中的字符串中刪除非UTF-8字符
例如,問題推文可能看起來這樣:
相機?
這是我使用的代碼:
with open("Tweets.txt",'w') as f:
for user_tws in twitter.get_user_timeline(screen_name='camera',
count = 200):
try:
f.write(user_tws["text"] + '\n')
except UnicodeEncodeError:
print("skipped: " + user_tws["text"])
mod_tw = user_tws["text"]
mod_tw=mod_tw.encode('utf-8','replace').decode('utf-8')
print(mod_tw)
f.write(mod_tw)
的錯誤是這樣的:
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f3a5' in position 56: character maps to