[英]TypeError: expected a character buffer object in Python
我不知道為什么無法將此document
寫入文件:
document=['', 'feeling frisky cool cat hits join us', 'askjoe app add music videos free today saintkittsandnevis', 'give dog flea bath midnight greeeeat smells like dawn', 'cat finds flash drive spent weeks looking', 'downside cat dude means can recognize nice smell pee second', 'louis pine apple make life brighter like star please follow me', 'gonna need nice cup coffee morning', 'gonna need nice cup coffee morning', 'iphone gives warning dies smh']
這是寫入文件的代碼:
with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
cleaned_tweet_file.write(document)
這是我得到的錯誤:
Traceback (most recent call last):
File "test.py", line 85, in <module>
cleaned_tweet_file.write(document)
TypeError: expected a character buffer object
write()
方法write()
str
而不是list
對象作為參數。 這是導致TypeError
的原因,將其包裝在str()
調用中只是給您 list
對象documents
的字符串表示形式,而不是列表本身的字符串表示形式 。
通過使用:
with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
cleaned_tweet_file.write(str(document))
您將獲得以字符串形式寫入文件的list
對象,因此有一個很大的字符串:
"['', 'feeling frisky cool cat hits join us', 'askjoe app add music videos free today saintkittsandnevis', 'give dog flea bath midnight greeeeat smells like dawn', 'cat finds flash drive spent weeks looking', 'downside cat dude means can recognize nice smell pee second', 'louis pine apple make life brighter like star please follow me', 'gonna need nice cup coffee morning', 'gonna need nice cup coffee morning', 'iphone gives warning dies smh']"
將存在。 邏輯上不是您追求的。
可以通過將file.writelines()
與字符串list
一起使用,或者將file.write()
與for
循環結合使用,而不是將list
手動(也可能是錯誤地)將list
轉換為str
使用writelines()
:
with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
cleaned_tweet_file.writelines(document)
此處無需循環或手動轉換。
使用write
和一個簡單的for
循環:
with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
for tweet in document:
cleaned_tweet_file.write(tweet)
這具有完全相同的效果。 它的主要優點是它允許您在每行基礎上指定其他內容。 如果您需要為每個tweet添加一個換行符和一個前綴,則可以顯式添加它cleaned_tweet_file.write("Tweet: " + tweet + "\\n")
。
這是解決方案,添加str
:
with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
cleaned_tweet_file.write(str(document))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.