我正在尝试删除除字母和空格之外的所有字符。
这就是我的代码的样子。
如果sampletext.txt包含具有多个字符的单词,我将结果写入removed.txt。
当我运行这段代码时。我在removed.txt 中只得到空白
import re
import sys
filename = open("removed.txt",'w')
sys.stdout = filename
from string import ascii_letters
allowed = set(ascii_letters + ' ')
with open("/Desktop/stem_analysis/sampletext.txt", 'r') as f:
answer = ''.join(l for l in f if l in allowed)
print(answer)
我的代码有什么问题
最佳答案
I am trying to remove all characters except alphabets along with the spaces.
我不是 100% 确定您要做什么,但是要删除除字母和空格之外的所有字符,您可以使用类似以下内容的内容:
with open("old_file.txt", "r") as f, open("new_file.txt", "w") as n:
x = f.read()
result = re.sub("[^a-z\s]", "", x, 0, re.IGNORECASE | re.MULTILINE)
n.write(result)
<小时/>
正则表达式说明:
<小时/>关于python - 读取文本文件并删除Python中除字母和空格之外的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53711324/