我试图删除字符串中的所有标点符号,但每当我运行我的程序什么都没有发生。。。这是我的代码:
#OPEN file (a christmas carol)
inputFile = open('H:\Documents\Computing\GCSE COMPUTING\Revision\Practice Prog/christmascarol.txt')
carolText = inputFile.read()
#CONVERT everything into lowercase
for line in carolText:
carolTextlower = carolText.lower()
#REMOVE punctuation (Put a space instead of a hyphened word or apostrophe)
import string
exclude = set(string.punctuation)
noPunctu = carolTextlower.join(ch for ch in carolTextlower if ch not in exclude)
print(noPunctu)
当我运行程序时,什么也没有出现
下面是如何打开一个文件,替换其中的某个字符,然后将所有内容重新写入新文件。在
使用以下代码检查:
这是您代码的修复版本。在
通常的Python约定是将
import
语句放在脚本的顶部,这样就很容易找到它们。在注意,我在文件名中使用了一个原始字符串(在左引号前用
r
表示)。这里没有严格的必要,但是它可以防止Windows路径中的反斜杠序列被解释为转义序列。例如在'H:\Documents\new\test.py'
中,\n
将被解释为换行符,\t
将被解释为制表符。在你真的应该在读(写)完一个文件后关闭它。但是,最好使用
^{pr2}$with
关键字来打开文件:这样可以确保即使出现错误也能正确关闭文件。例如相关问题 更多 >
编程相关推荐