我有一个名为的文件messages.txt
,其中包含许多用行分隔的句子。我试图排除包含非字母字符的行(我只想要那些包含 AZ 字符的行。
import re
import string
lines = [line.rstrip() for line in open('messages.txt', encoding='utf-8')]
cleaned_lines = [s.replace("!", "").replace(".", "").replace("?", "").replace(",", "") for s in lines]
output_lines = []
for line in cleaned_lines:
if line.replace(' ', '').isalpha() == True:
output_lines.append(re.sub(r'\W+', '', line.lower()))
chars = sorted(set(('').join(output_lines)))
print(chars)
输出:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ª', 'â', 'ã', 'å', 'ð', 'ÿ', 'œ', 'š', 'ž', 'ƒ', 'ˆ']
可以看出,似乎 isalpha() 方法并没有排除奇怪的
'â', 'ã', 'å', 'ð', 'ÿ'
人物。我有一种感觉,这可能是由于正在读取文件的编码,但是,我认为 isalpha 方法与模式 RegEx 结合应该能够过滤掉这些字符。
这是故意的吗?如果是这样,有什么方法可以去除这些奇怪的字符?