如何获取文本文件中的所有唯一字符? UNIX /蟒蛇

时间:2014-02-03 07:57:36

标签: python unix character text-files unique

有没有其他方法可以获取文本文件中所有唯一字符的列表?

我尝试过以下方式,但有更多的pythonic方式吗?可以在unix命令中实现相同的输出吗?

>>> import codecs
>>> from collections import Counter
>>> with codecs.open('my.txt','r','utf8') as fin:
...     x = Counter(fin.read())
...     print [i for i in x if len(i) == 1]
... 
[u'\u2014', u'\u2018', u'\u201c', u' ', u'\xa3', u'$', u'(', u',', u'0', u'4', u'8', u'@', u'D', u'H', u'L', u'P', u'T', u'\xd7', u'X', u'`', u'd', u'h', u'l', u'p', u't', u'x', u'\ufffd', u'\ufeff', u'\u2013', u'#', u"'", u'+', u'/', u'3', u'7', u';', u'?', u'C', u'G', u'K', u'O', u'S', u'W', u'_', u'\xe0', u'c', u'g', u'k', u'\u2026', u'o', u's', u'w', u'\n', u'"', u'&', u'*', u'\xad', u'.', u'2', u'6', u':', u'>', u'B', u'F', u'J', u'N', u'R', u'V', u'Z', u'b', u'f', u'\xe9', u'j', u'n', u'r', u'v', u'z', u'\t', u'\u2019', u'\u201d', u'!', u'%', u')', u'-', u'1', u'5', u'9', u'=', u'A', u'\xc2', u'E', u'I', u'M', u'Q', u'U', u'Y', u'a', u'\xe2', u'e', u'i', u'm', u'q', u'u', u'y']

1 个答案:

答案 0 :(得分:3)

一种方法是使用集合:

fh = open('my.txt','r').read()
unique_chars = set(fh)
len(unique_chars) #for the length.