【问题标题】:Troubles with Counter Object计数器对象的问题
【发布时间】:2014-02-10 14:46:50
【问题描述】:

我有一个包含 Unicode 字符串的文件,我正在计算单词并使用 Counter Object 对其进行排序

这是我的代码

import collections
import codecs
from collections import Counter

with io.open('1.txt', 'r', encoding='utf8') as infh:
    words =infh.read()
    Counter(words)
    print Counter(words).most_common(10000)

这是我的 1.txt 文件

വാര്‍ത്തകള്‍ വാര്‍ത്തകള്‍ വാര്‍ത്തകള്‍  വാര്‍ത്തകള്‍    വാര്‍ത്തകള്‍   വാര്‍ത്തകള്‍   വാര്‍ത്തകള്‍ വാര്‍ത്തകള്‍ 

它为我提供字符数而不是字数 像这样

[(u'\u0d4d', 63), (u'\u0d24', 42), (u'\u200d', 42), (u'\n', 26), (u' ', 21), (u'\u0d30', 21), (u'\u0d33', 21), (u'\u0d35', 21), (u'\u0d15', 21), (u'\u0d3e', 21)]

我的代码有什么问题?

【问题讨论】:

  • words = infh.read().split()

标签: python regex python-2.7 unicode


【解决方案1】:

Counter 在其构造函数中采用可迭代的元素。 infh.read() 返回一个字符串,该字符串在迭代时返回单个字符。相反,您需要提供一个单词列表:Counter(infh.read().split())

如果您想稍后将计数写入文件:

with open('file.txt', 'wb') as f:
    for word, count in Counter(words).most_common(10000):
        f.write(u'{} {}\n'.format(word, count))

【讨论】:

  • 好的,如何将这个计数写入文件?
  • @karu,考虑到f已经在wb模式下打开:for word, count in Counter(words).most_common(10000): f.write('{} {}\n'.format(word, count))
  • 文件 "/home/akallararajappan/corpus/counter.py",第 9 行,在 f.write('{} {}\n'.format(word, count)) UnicodeEncodeError : 'ascii' 编解码器无法对位置 0-11 中的字符进行编码:序数不在范围内(128)
  • @karu,尝试在格式字符串中添加u 修饰符。
  • u'{} {}\n'.format(word, count).encode('utf-8') 应该可以解决问题。
猜你喜欢
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 2010-12-27
  • 2010-10-04
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多