【问题标题】:How do I get the words in alphabetical order and remove the symbol u'?如何按字母顺序获取单词并删除符号 u'?
【发布时间】:2017-12-28 05:06:46
【问题描述】:

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

df = pd.read_csv('Twidb11.csv',error_bad_lines=False, sep='delimiter',  engine='python')
# Creating Bag of Words
count_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 ....}

【问题讨论】:

    标签: python-2.7 machine-learning sentiment-analysis


    【解决方案1】:

    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))) # converted string unicode into 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)))
    

    【讨论】:

      猜你喜欢
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2016-10-01
      • 2012-12-20
      • 1970-01-01
      相关资源
      最近更新 更多