UnicodeEncodeError:“cp949”编解码器无法对ch进行编码

2024-04-19 20:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我该怎么处理?

wfile.write(数据['text']+'\n')

UnicodeEncodeError:“cp949”编解码器无法编码字符

import tweepy
import time
import os
import json

search_term1 = '' 
search_term2 = ''  

lat = ""
lon = ""
radius = ""
location = "%s,%s,%s" % (lat, lon, radius)  

auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(Access_token, Access_token_secret)

api = tweepy.API(auth)      

c=tweepy.Cursor(api.search,
            q="{}+OR+{}".format(search_term1, search_term2),   
            rpp=1000,    
            geocode=location, 
            include_entities=True)


wfile = open(os.getcwd()+"/test1.txt", mode='w')   
data = {}
i = 1
for tweet in c.items():            

    data['text'] = tweet.text
    print(i, ":", data)
    wfile.write(data['text']+'\n')  
    time.sleep(0.5)                 
    i += 1

wfile.close()

我是通过修改Internet来得到这个错误的。

TypeError:write()不接受关键字参数

wfile.write(data['text']+'\n',encoding='UTF8')  

TypeError:write()只接受一个参数(给定2个)

 wfile.write(data['text']+'\n','utf-8')  

Tags: term1textimporttokenauthapisearchdata
1条回答
网友
1楼 · 发布于 2024-04-19 20:38:04

cp949是Windows系统的默认区域设置,这就是open()的默认值。从^{} documentation

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used.

打开文件时指定其他编解码器:

wfile = open(os.getcwd()+"/test1.txt", mode='w', encoding='utf8')   

请注意,在打开没有路径的文件时,不需要预先挂起os.getcwd(),默认情况下,将工作目录用于相对路径:

wfile = open("test1.txt", mode='w', encoding='utf8')   

最好使用os.path.join()为其他所有内容构建路径。

否则,可以使用enumerate()和上下文管理器进一步简化代码。这里的data字典不是很有用,只要在任何地方引用tweet.text

with open(os.getcwd()+"/test1.txt", mode='w') as wfile:
    for i, tweet in enumerate(c.items()):
        print("{}: {}".format(i, tweet.text))
        wfile.write(tweet.text + '\n')
        time.sleep(0.5)

相关问题 更多 >