如何按字母顺序排列单词并删除符号u’?

我正在创建一个词袋。我参考了这个链接 https://pythonprogramminglanguage.com/bag-of-words/#respond

df = pd.read_csv('Twidb11.csv',error_bad_lines=False, sep='delimiter',  engine='python')# Creating Bag of Wordscount_vect = CountVectorizer()X_train_counts = count_vect.fit_transform(df.Text)print count_vect.fit_transform(df.Text).todense()#X_train_counts.shape print count_vect.vocabulary_

它给我提供了单词及其频率,但单词没有按字母顺序排列,并且有u’符号,如下所示。如何去除这些问题?

输出 : { u’binance’: 28, u’they’: 139, u’just’: 83, u’global’: 67, u’alternatives’: 11, u’zcash’: 168, u’years’: 165, u’talks’: 133, u’japan’: 82, u’yes’: 166, u’25’: 1, u’chinese’: 37, u’6000′: 5, u’zzzpositive’: 170, u’winner’: 162, u’28’: 2, u’actually’:12 ….}


回答:

u 是Unicode的表示。如果你不想要它,可以使用 str() 将其转换为字符串

1) 将Unicode字符串转换为字符串,

>>> my_dict = {str(i):j for i,j in my_dict.items()}>>> print my_dict>>> {'binance': 28, 'global': 67, 'chinese': 37, 'just': 83, '25': 1, 'zzzpositive': 170, 'alternatives': 11, '6000': 5, 'winner': 162, '28': 2, 'zcash': 168, 'actually': 12, 'they': 139, 'talks': 133, 'japan': 82, 'yes': 166, 'years': 165}

2) 对my_dict进行排序,

itemgetter会帮助你更容易地完成这个任务

>>> from operator import itemgetter>>> dict(sorted(my_dict.items(), key=itemgetter(1))) # 将Unicode字符串转换为str>>> {'25': 1, 'winner': 162, 'chinese': 37, '6000': 5, 'binance': 28, 'zzzpositive': 170, 'alternatives': 11, 'just': 83, 'global': 67, '28': 2, 'zcash': 168, 'actually': 12, 'they': 139, 'talks': 133, 'japan': 82, 'yes': 166, 'years': 165}>>> 

一行代码完成,

>>> dict(sorted({str(i):j for i,j in my_dict.items()}.items(), key=itemgetter(1)))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注