获取文本文件中存在的所有唯一字符的列表(有例外)(Python)

时间:2017-08-03 01:26:03

标签: python

我希望获得除

之外的文本文件中所有字符的列表
[A-Z], [0-9], '|', '~'. 

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

第1步:读入您的文件并将其转换为一组字符。

charset = set(open('file.txt').read())

第2步:将其加回到包含str.join的字符串,以便进行下一步。

chars = ''.join(charset)

第3步:使用正则表达式,用''替换所有不需要的字符,然后显示

import re
filtered_chars = re.sub('[A-Z0-9|~]', '', chars)

print(set(filtered_chars))

其他参考文献(类似于您的使用案例,但不完全相同):

  1. List of all unique characters in a string?

  2. How to get all unique characters in a textfile? unix/python

  3. Regular Expression: Any character that is NOT a letter or number