我想把所有的标点符号从文本文件中去掉。有没有更有效的方法来做到这一点?
这是我的代码:

fname = open("text.txt","r")

stripped = ""
for line in fname:
    for c in line:
        if c in '!,.?-':
            c = ""
        stripped = stripped + c
print(stripped)

最佳答案

可以尝试使用正则表达式,用空字符串替换任何标点字符:

import re
with open('text.txt', 'r') as f:
    for line in f:
        print(re.sub(r'[.!,?-]', '', line)

10-08 11:20