簡體   English   中英

TypeError:應為Python中的字符緩沖區對象

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM