python - 读取文本文件并删除Python中除字母和空格之外的所有字符

标签 python python-3.x

我正在尝试删除除字母和空格之外的所有字符。
这就是我的代码的样子。
如果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)
<小时/>

正则表达式说明:

enter image description here

<小时/>

Regex Demo

关于python - 读取文本文件并删除Python中除字母和空格之外的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53711324/

相关文章:

python - vim:使用 python 的 omnifunc 错误完成代码

python - 在Python 3和Python 2中处理CSV中的非UTF8字符

Python:使用类变量来跟踪所有对象

python - 检查python脚本是否正在运行

python - 如何在 matplotlib 中创建非线性颜色条刻度

python - 以公制前缀为对象的减法

拆分字符串并解压缩为变量的 Pythonic 方法?

python - 按需执行存储在变量中的类函数

python - 如何在多处理参数中使用函数指针

python - 使用 tkinter 将文件路径从浏览按钮放入全局变量中