TypeError:需要一个类似字节的对象,而不是'str':即使使用编码

时间:2018-08-16 14:19:59

标签: python encode

我只是想打印我的脚本。我遇到了这个问题,已经研究并阅读了许多答案,甚至添加.encode('utf-8)仍然无法正常工作。

import pandas
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation

n_components = 30
n_top_words = 10

def print_top_words(model, feature_names, n_top_words):]
    for topic_idx, topic in enumerate(model.components_):
        message = "Topic #%d: " % topic_idx 
        message += " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])

        return message

text = pandas.read_csv('fr_pretraitement.csv', encoding = 'utf-8')
text_clean = text['liste2']
text_raw = text['liste1']
text_clean_non_empty = text_clean.dropna()
not_commas = text_raw.str.replace(',', '')
text_raw_list = not_commas.values.tolist()
text_clean_list = text_clean_non_empty.values.tolist()

tf_vectorizer = CountVectorizer()
tf = tf_vectorizer.fit_transform(text_clean_list)
tf_feature_names = tf_vectorizer.get_feature_names()

lda = LatentDirichletAllocation(n_components=n_components, max_iter=5,
                            learning_method='online',
                            learning_offset=50.,
                            random_state=0)

lda.fit(tf)

print('topics...')
print(print_top_words(lda, tf_feature_names, n_top_words))


document_topics = lda.fit_transform(tf)
topics = print_top_words(lda, tf_feature_names, n_top_words)
for i in range(len(topics)):
    print("Topic {}:".format(i))
    docs = np.argsort(document_topics[:, i])[::-1]
    for j in docs[:300]:
       cleans = " ".join(text_clean_list[j].encode('utf-8').split(",")[:2])    
       print(cleans.encode('utf-8') + ',' + " ".join(text_raw_list[j].encode('utf-8').split(",")[:2]))

我的输出:

  

回溯(最近通话最近一次):

     

中的文件“ script.py”,第62行      

cleans =“” .join(text_clean_list [j] .encode('utf-8')。split(“,”)[:2])

     

TypeError:需要一个类似字节的对象,而不是'str'

2 个答案:

答案 0 :(得分:1)

cleans = " ".join(text_clean_list[j].encode('utf-8').split(",")[:2])

您要将 text_clean_list [j] 中的 string 编码为 bytes ,但是split(“,”)呢?

“,” 仍然是 str 。现在,您尝试使用字符串拆分类似对象的字节。

示例:

a = "this,that"
>>> a.encode('utf-8').split(',')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

修改

解决方案: 1-一种解决方案可能是不立即编码您的字符串对象,只是先拆分然后再编码。就像我的例子一样:

a = "this, that"
c = a.split(",")
cleans = [x.encode('utf-8') for x in c]

2-只需使用“,”本身的简单编码即可。

cleans = a.encode("utf-8").split("b")

两者都得出相同的答案。如果您只想提供输入和输出示例,那就更好了。

答案 1 :(得分:1)

让我们看一下引发错误的行:

cleans = " ".join(text_clean_list[j].encode('utf-8').split(",")[:2])

让我们一步一步走:

  • text_clean_list[j] str 类型=>直到那里都没有错误
  • text_clean_list[j].encode('utf-8') bytes 类型=>直到那里都没有错误
  • text_clean_list[j].encode('utf-8').split(",")是错误的:传递给split()方法的参数“,”为 str 类型,但必须为 bytes 类型(因为这里split()是来自 bytes 对象的方法)=>会引发错误,指示a bytes-like object is required, not 'str'

注意:将split(",")替换为split(b",")可以避免该错误(但可能不是您期望的行为...)