gpt4 book ai didi

python - 统一码编码错误 : 'cp949' codec can't encode character

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:29 36 4
gpt4 key购买 nike

我该如何处理?

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

UnicodeEncodeError: 'cp949' codec can't encode character

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()

我通过修改互联网得到这个错误。

TypeError: write() 没有关键字参数

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

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

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

最佳答案

cp949 是 Windows 系统的默认语言环境,也是 open() 的默认语言环境。来自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)

关于python - 统一码编码错误 : 'cp949' codec can't encode character,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821262/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com