gpt4 book ai didi

Python 3.6 - 从文件中读取编码文本并转换为字符串

转载 作者:太空狗 更新时间:2023-10-30 02:55:23 26 4
gpt4 key购买 nike

希望有人能帮我解决以下问题。它可能并不太复杂,但我一直无法弄清楚。我的“output.txt”文件是用以下内容创建的:

f = open('output.txt', 'w')
print(tweet['text'].encode('utf-8'))
print(tweet['created_at'][0:19].encode('utf-8'))
print(tweet['user']['name'].encode('utf-8'))
f.close()

如果我不对它进行编码以写入文件,它会给我错误。所以“输出”包含 3 行 utf-8 编码输出:

b'testtesttest'
b'line2test'
b'\xca\x83\xc9\x94n ke\xc9\xaan'

在“main.py”中,我试图将其转换回字符串:

f = open("output.txt", "r", encoding="utf-8")
text = f.read()
print(text)
f.close()

遗憾的是,b'' - 格式仍未删除。我还需要解码吗?如果可能的话,我想保留 3 行结构。对于新手问题,我深表歉意,这是我在 SO 上的第一个问题 :)

提前致谢!

最佳答案

在回答我问题的人们的帮助下,我已经能够让它发挥作用。解决方案是更改写入文件的方式:

     tweet = json.loads(data)
tweet_text = tweet['text'] # content of the tweet
tweet_created_at = tweet['created_at'][0:19] # tweet created at
tweet_user = tweet['user']['name'] # tweet created by
with open('output.txt', 'w', encoding='utf-8') as f:
f.write(tweet_text + '\n')
f.write(tweet_created_at+ '\n')
f.write(tweet_user+ '\n')

然后像这样阅读:

    f = open("output.txt", "r", encoding='utf-8')
tweettext = f.read()
print(text)
f.close()

关于Python 3.6 - 从文件中读取编码文本并转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635244/

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